/*****多线程下载实例****/ @interface ViewController () <NSURLSessionDownloadDelegate> @property (weak, nonatomic) IBOutlet HMDownloadButton *progressButton; @property (nonatomic, strong) NSURLSession *session; // 下载任务 @property (nonatomic, strong) NSURLSessionDownloadTask *downloadTask; // 续传数据 @property (nonatomic, strong) NSData *resumeData; @end @implementation ViewController - (NSURLSession *)session { if (_session == nil) { NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; _session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil]; } return _session; } // 开始 - (IBAction)start { NSString *urlString = @"http://download.ime.sogou.com/1411725208/sogou_mac_30a.dmg?st=iPW0jnPMdGHl-Or5UhcbAw&e=1416824560&fn=sogou_mac_30a.dmg"; urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:urlString]; // 在 NSURLConnection中是在代理方法中计算下载进度,NSURLSession同样是通过代理 self.downloadTask = [self.session downloadTaskWithURL:url]; // 任务默认是挂起的,别忘了继续 [self.downloadTask resume]; } // 暂停-下载任务 - (IBAction)pause { // 暂停下载任务,如果再次暂停,因为downloadTask没有工作,所以续传数据长度为0 // 解决办法,一旦暂停,就不能再次点击! [self.downloadTask cancelByProducingResumeData:^(NSData *resumeData) { NSLog(@"暂停 %tu", resumeData.length); self.resumeData = resumeData; // 释放 downloadTask self.downloadTask = nil; }]; } // 继续 - (IBAction)resume { if (self.resumeData == nil) { return; } // 发起续传的下载任务 self.downloadTask = [self.session downloadTaskWithResumeData:self.resumeData]; [self.downloadTask resume]; // 任务一旦启动,续传数据就没用了 self.resumeData = nil; } #pragma mark - 下载代理方法 // 1. 下载完成 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location { NSLog(@"下载完成"); } // 2. 下载进度 /** bytesWritten 本次下载大小 totalBytesWritten 已经下载大小 totalBytesExpectedToWrite 文件总大小 */ - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { float progress = (float)totalBytesWritten / totalBytesExpectedToWrite; NSLog(@"%.02f %@", progress, [NSThread currentThread]); dispatch_async(dispatch_get_main_queue(), ^{self.progressButton.progress = progress;}); } @end
原文地址:http://blog.csdn.net/u014656271/article/details/43992283