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