通过NSURLSessionDownloadTask代理实现下载大文件


//
//  ViewController.m
//  NSURLSessionDownloadTask
//
//  Created by hq on 16/4/17.
//  Copyright © 2016年 hanqing. All rights reserved.
//

#import "ViewController.h"

@interface ViewController () <NSURLSessionDownloadDelegate>

@property (weak, nonatomic) IBOutlet UIButton *startBut;

@property (weak, nonatomic) IBOutlet UIProgressView *pro;

- (IBAction)startDownload:(UIButton *)sender;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (IBAction)startDownload:(UIButton *)sender {
    
    
    NSURLSession *session=[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];
    
    
    NSString *urlString=@"http://120.25.226.186:32812/resources/videos/minion_01.mp4";
    
    NSURLSessionDownloadTask *task=[session downloadTaskWithURL:[NSURL URLWithString:urlString]];
    
    //恢复下载任务
    [task resume];
    
    self.startBut.enabled=NO;
    
}

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    
    NSLog(@"已下载%lld",totalBytesWritten);
    
    NSLog(@"文件总大小%lld",totalBytesExpectedToWrite);
    
    //self.pro.progress=(1.0*totalBytesWritten/totalBytesExpectedToWrite);
    
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        
        //必须放在主线程当中才回更新进度条-----------------------------
        self.pro.progress=(1.0*totalBytesWritten/totalBytesExpectedToWrite);
    }];

}


-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
    
    //NSLog(@"%@",location);
    
    //下载完成,将文件剪切到我们的cache文件夹当中去
    NSString *cachePath=NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    
    NSString *fileName=[cachePath stringByAppendingPathComponent:@"video.mp4"];
    
    NSFileManager *fileManager=[NSFileManager defaultManager];
    
    [fileManager moveItemAtURL:location toURL:[NSURL fileURLWithPath:fileName] error:nil];
    
    NSLog(@"%@",fileName);
    
}


//不管下载成功还是失败,都会来到该方法,不过下载失败的话,error有值,下载成功error为null
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
    
    if (error) {
        
        NSLog(@"下载失败了%@",error);
    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值