NSURLSession中的downloadTask的使用
1.用downloadTask下载图片
优点:简单
缺点:不能监听下载的进度
代码示例:
NSURL *url = [NSURL URLWithString:@"http://pic1.win4000.com/pic/b/03/21691230681.jpg"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) { //默认把数据写到磁盘中:tmp/...随时可能被删除 NSLog(@"location= %@", location); //转移文件 NSString *cache = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; NSString *filePath = [cache stringByAppendingPathComponent:response.suggestedFilename]; NSLog(@"filePath = %@",filePath); NSURL *toURL = [NSURL fileURLWithPath:filePath]; [[NSFileManager defaultManager] moveItemAtURL:location toURL:toURL error:nil]; }]; [downloadTask resume];
2.downloadTask下载比较大的文件
优点:已经解决内存飚升的问题
缺点:无法实现断点下载的功能
代码如下:
#import "ViewController.h" @interface ViewController ()<NSURLSessionDownloadDelegate> @property (nonatomic,strong) NSURLSession *session; @property (nonatomic,strong) NSURLSessionDownloadTask *downloadTask; @property (nonatomic,strong) NSData *resumeData ; @end @implementation ViewController - (IBAction)startClick:(id)sender { [self.downloadTask resume]; } - (IBAction)suspendClick:(id)sender { [self.downloadTask suspend]; } - (IBAction)cancleClick:(id)sender { //用cancel的方法,操作不可以恢复 // [self.downloadTask cancel]; //取消,可以恢复的取消操作 //resumeDta可以用来恢复下载的数据 [self.downloadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) { //data不是沙盒中已经下载好的数据 self.resumeData = resumeData; }]; self.downloadTask = nil; } - (IBAction)resumeClick:(id)sender { //在恢复下载的时候,判断是否可以用来进行恢复下载的数据,如果有那么就根据该数据创建一个新的网络请求 if (self.resumeData) { //取消 再恢复,在恢复的时候,需要重新创建 self.downloadTask = [self.session downloadTaskWithResumeData:self.resumeData]; } [self.downloadTask resume]; } - (NSURLSession *)session { if (!_session) { _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]]; } return _session; } - (NSURLSessionDownloadTask *)downloadTask { if (!_downloadTask) { NSURL *url = [NSURL URLWithString:@"http://meiye-mbs.oss-cn-shenzhen.aliyuncs.com/mbsFiles/0e3d0e4a0d5d4da5963e9e7617e8de101565841097849.mp4"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; _downloadTask = [self.session downloadTaskWithRequest:request]; } return _downloadTask; } #pragma mark - 代理 //01 写数据的时候调用 /** bytesWritten:本次写入的数据大小 totalBytesWritten:写入数据的总大小 totalBytesExpectedToWrite:文件的总大小 */ - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { NSLog(@"111111=%f", 1.0 * totalBytesWritten / totalBytesExpectedToWrite); } //02 下载完成的时候调用 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location { //转移文件 NSString *cache = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; NSString *filePath = [cache stringByAppendingPathComponent:downloadTask.response.suggestedFilename]; NSLog(@"filePath = %@",filePath); NSURL *toURL = [NSURL fileURLWithPath:filePath]; [[NSFileManager defaultManager] moveItemAtURL:location toURL:toURL error:nil]; } //03 整个请求结束或者失败的时候调用 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { NSLog(@"结束"); } @end