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
| //1-代理 @interface ViewController ()<NSURLSessionDownloadDelegate> @end
//2-task -(void)downloadTaskWithURLNoHandler { NSURLSessionConfiguration *cfg=[NSURLSessionConfiguration defaultSessionConfiguration]; //得到session对象 NSURLSession *session=[NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]]; NSURL *url=[NSURL URLWithString:@"http://localhost:8080/MJServer/resources/videos/minion_01.mp4"]; //如果给下载任务设置了completionHandler这个block,也实现了下载的代理方法,优先执行block NSURLSessionDownloadTask *task=[session downloadTaskWithURL:url]; // NSURLSessionDownloadTask *task=[session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) { // NSLog(@"下载完毕"); // // }]; //开始任务 [task resume]; } //3-delegate #pragma mark-NSURLSessionDownloadDelegate //下载完毕 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location { NSLog(@"下载didFinishDownloadingToURL--%@",location); NSString *caches=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject]; NSString *file=[caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename]; NSFileManager *mgr=[NSFileManager defaultManager]; //AtPath:剪切前的文件路径 //toPath:剪切后的文件路径 [mgr moveItemAtPath:location.path toPath:file error:nil]; } //恢复下载 -(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes { } //下载任务,写完一部分就调用 //bytesWritten:本次写了多少 //totalBytesWritten:累计写了多少长度到沙盒中 //totalBytesExpectedToWrite:文件的总长度
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { double progress=(double)totalBytesWritten/totalBytesExpectedToWrite; NSLog(@"下载进度--%f",progress); }
|