導語
-
現在NSURLConnection在開發中會使用的越來越少,iOS9已經將NSURLConnection廢棄,現在最低版本一般適配iOS7,所以也可以使用。
- NSURLConnection相對於NSURLSession,安全性低。NSURLConnection下載有峰值,比較麻煩處理。
- 盡管適配最低版本iOS7,也可以使用NSURLSession。AFN已經不支持NSURLConnection。
- NSURLSession:默認是掛起狀態,如果要請求網絡,需要開啟。
[NSURLSession sharedSession] 獲取全局的NSURLSession對象。在iPhone的所有app共用一個全局session.
NSURLSessionUploadTask -> NSURLSessionDataTask -> NSURLSessionTask
NSURLSessionDownloadTask -> NSURLSessionTask
NSURLSessionDownloadTask下載,默認下載到tmp文件夾。下載完成后刪除臨時文件。所以我們要在刪除文件之前,將它移動到Cache里。
NSURLSession詳解
-
NSURLSession基礎
- NSURLSession代理
- NSURLSession大文件下載
- NSURLSession斷點續傳
1.NSURLSession基礎
- 第一種網絡請求方法
//創建URL NSURL * url = [NSURL URLWithString:@"http://192.168.1.200/login.php?username=haha&password=123"]; //創建請求 // NSURLRequest * request = [NSURLRequest requestWithURL:url]; //創建Session NSURLSession * session = [NSURLSession sharedSession]; //創建任務 NSURLSessionDataTask * task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); }]; //開啟網絡任務 [task resume];
- 第二種網絡請求方法
//創建URL NSURL * url = [NSURL URLWithString:@"http://192.168.1.200/login.php?username=haha&password=123"]; //創建請求 NSURLRequest * request = [NSURLRequest requestWithURL:url]; //創建Session NSURLSession * session = [NSURLSession sharedSession]; //創建任務 NSURLSessionDataTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); }]; //開啟網絡任務 [task resume];
- POST請求
NSURL * url = [NSURL URLWithString:@"http://192.168.1.200/login.php"]; NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url]; //設置請求方法 request.HTTPMethod = @"POST"; //設置請求體 request.HTTPBody = [@"username=haha&password=123" dataUsingEncoding:NSUTF8StringEncoding]; [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); }] resume];
- 下載文件
NSURL * url = [NSURL URLWithString:[@"http://192.168.1.200/DOM解析.mp4" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; NSURLSession * session = [NSURLSession sharedSession]; NSURLSessionDownloadTask * downloadTask = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) { //location 下載到沙盒的地址 NSLog(@"下載完成%@",location); //response.suggestedFilename 響應信息中的資源文件名 NSString * cachesPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename]; NSLog(@"緩存地址%@",cachesPath); //獲取文件管理器 NSFileManager * mgr = [NSFileManager defaultManager]; //將臨時文件移動到緩存目錄下 //[NSURL fileURLWithPath:cachesPath] 將本地路徑轉化為URL類型 //URL如果地址不正確,生成的url對象為空 [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:cachesPath] error:NULL]; }]; [downloadTask resume];
2.NSURLSession代理
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { // 全局session // NSURLSession * session = [NSURLSession sharedSession]; //創建自定義session //NSURLSessionConfiguration 的 配置 //[[NSOperationQueue alloc] init] 也可以寫成 nil NSURL * url = [NSURL URLWithString:@"http://192.168.1.200/login.php?username=haha&password=123"]; NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]]; NSURLSessionDataTask * task = [session dataTaskWithURL:url]; [task resume]; } //接收到服務器響應 - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler { NSLog(@"%s",__FUNCTION__); //允許接受服務器回傳數據 completionHandler(NSURLSessionResponseAllow); } //接收服務器回傳的數據,有可能執行多次 - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); } //請求成功或失敗 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { NSLog(@"%@",error); }
3.NSURLSession大文件下載
#import "ViewController.h" @interface ViewController ()<NSURLSessionDownloadDelegate> @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. NSLog(@"%@",NSSearchPathForDirectoriesInDomains(9, 1, 1)); } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]]; NSURLSessionDownloadTask * task = [session downloadTaskWithURL:[NSURL URLWithString:[@"http://192.168.1.200/DOM解析.mp4"stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]; [task resume]; } /* 監測臨時文件下載的數據大小,當每次寫入臨時文件時,就會調用一次 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); }
4.NSURLSession斷點續傳
#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.68/丁香花.mp3"stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]; [self.task resume]; } //故事板中暫停按鈕的響應方法 - (IBAction)pause:(id)sender { //暫停就是將任務掛起 [self.task cancelByProducingResumeData:^(NSData *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); }