之前本來打算在寫兩個篇幅,但是在這片開寫的時候覺得還是寫一個比較好,有利於理解。NSURLSession下載是通過NSURLSession下載代理實現的,上一片也介紹了代理,之所以沒有介紹下載是因為,我個人覺得容易混淆(應該是我太笨)。這篇隨筆里將會介紹NSURLSession下載的實現,包括下載的
之前本來打算在寫兩個篇幅,但是在這片開寫的時候覺得還是寫一個比較好,有利於理解。NSURLSession下載是通過NSURLSession下載代理實現的,上一片也介紹了代理,之所以沒有介紹下載是因為,我個人覺得容易混淆(應該是我太笨)。這篇隨筆里將會介紹NSURLSession下載的實現,包括下載的開始,掛起,繼續。希望本片可以給大家帶來點點收穫。下一篇我打算介紹一下AFN畢竟實際開發中AFN才是硬道理。
// // ViewController.m // NSURLSession大文件下載 // // Created by 大歡 on 16/3/21. // Copyright © 2016年 大歡. All rights reserved. // #import "ViewController.h" @interface ViewController ()<NSURLSessionDownloadDelegate> @property (nonatomic, strong) NSURLSessionDownloadTask * task; @property (nonatomic, strong) NSData * resumeData; @property (nonatomic, strong) NSURLSession * session; @end @implementation ViewController - (IBAction)start:(id)sender { NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]]; self.session = session; self.task = [session downloadTaskWithURL:[NSURL URLWithString:[@"http://192.168.1.200/DOM解析.mp4"stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]; [self.task resume]; } - (IBAction)pause:(id)sender { //暫停就是將任務掛起 [self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) { //保存已下載的數據 self.resumeData = resumeData; }]; } - (IBAction)resume:(id)sender { //可以使用ResumeData創建任務 self.task = [self.session downloadTaskWithResumeData:self.resumeData]; //開啟繼續下載 [self.task resume]; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. NSLog(@"%@",NSSearchPathForDirectoriesInDomains(9, 1, 1)); } /* 監測臨時文件下載的數據大小,當每次寫入臨時文件時,就會調用一次 bytesWritten 單次寫入多少 totalBytesWritten 已經寫入了多少 totalBytesExpectedToWrite 文件總大小 */ - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { //列印下載百分比 NSLog(@"%f",totalBytesWritten * 1.0 / totalBytesExpectedToWrite); } //下載完成 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location { NSString * cachesPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename]; NSFileManager * mgr = [NSFileManager defaultManager]; [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:cachesPath] error:NULL]; } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { NSLog(@"%@",error); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end