1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
| #import "ViewController.h"
@interface ViewController ()<NSURLSessionDownloadDelegate> @property (weak, nonatomic) IBOutlet UIProgressView *progressView; @property(nonatomic,strong) NSURLSessionDownloadTask *task; @property(nonatomic,strong) NSData *resumeData; @property(nonatomic,strong) NSURLSession *session;
@end
@implementation ViewController - (NSURLSession *)session { if (!_session) { NSURLSessionConfiguration *cfg=[NSURLSessionConfiguration defaultSessionConfiguration]; self.session= [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]]; } return _session; } - (IBAction)download:(UIButton *)sender { //按钮状态取反 sender.selected=!sender.isSelected; if(sender.selected){//继续下载 if(self.task==nil){ if (self.resumeData) { //有值,恢复 [self resume]; }else{ //从0开始 [self start]; } } }else{ //暂停 [self pause]; } } //开始 -(void)start{ //1-创建一个下载任务 NSURL *url=[NSURL URLWithString:@"http://localhost:8080/MJServer/resources/videos.zip"]; self.task=[self.session downloadTaskWithURL:url]; //2-开始任务 [self.task resume]; } //恢复,继续 -(void)resume { //传入上次暂停下载返回的数据,就可以恢复下载 self.task= [self.session downloadTaskWithResumeData:self.resumeData]; //开始下载 [self.task resume]; //清空 self.resumeData=nil; } //暂停 -(void)pause { __weak typeof(self) vc=self; [self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) { //resumeData:包含了继续下载的开始位置 vc.resumeData=resumeData; vc.task=nil; }]; } #pragma mark--delegate
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location { //文件路径 NSString *caches=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject]; NSString *filePath=[caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename]; //创建一个空的文件到沙盒中 NSFileManager *mgr=[NSFileManager defaultManager]; [mgr moveItemAtPath:location.path toPath:filePath error:nil]; }
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { self.progressView.progress=(double)totalBytesWritten/totalBytesExpectedToWrite; }
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes { } @end
|