前言:
無論 Android 還是 iOS,都離不開與伺服器通訊,這就必須用到網絡請求。2013 年我做 iOS 時用的是 ASIHTTPRequest,如今重拾起 iOS,它早已停止維護,大家都在用 AFNetworking。早期的 ASIHTTPRequest 與 AFNetworking 都是基於 NSURLConnection 實現的,而 iOS 9 之後 NSURLConnection 正式退%) 歷史舞台,取而代之的是 iOS 7 推出的 NSURLSession。本著追根溯源的原則,先學會用 NSURLSession 實作網絡請求,再去研究 AFNetworking 會更透徹。
了解 NSURLSession
NSURLSession 於 2013 年隨 iOS 7 發布,用於取代 NSURLConnection。它的使用方式相當" 便:根據會話對象建立一個 Task,然後執行即可。緩存、會話生命週期、多線程任務等細節,蘋果都在 SDK 層%) 被封裝好了。唯一") 遺憾的是,NSURLSession 只提供異步請求,沒有同步方式。
NSURLSession 使用
以下從最簡單的 GET 請求開始。
1)構造 URL 資源地址
// 構造URL資源地址 NSURL *url = [NSURL URLWithString:@"https://api.nohttp.net/method?name=yanzhenjie&pwd=123"];
2)建立 Request 請求對象
// 創建Request請求 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // 配置Request請求 // 設置請求方法 [request setHTTPMethod:@"GET"]; // 設置請求超時 默認超時時間60s [request setTimeoutInterval:10.0]; // 設置頭部參數 [request addValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"]; //或者下面這種方式 添加所有請求頭信息 request.allHTTPHeaderFields=@{@"Content-Encoding":@"gzip"}; //設置緩存策略 [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];可依需求加上請求方式、超時時間與請求頭等設定。這裡重點說明緩存策略:
3)建立 NSURLSession 會話對象
可以直接採用系統共享的會話:
// 采用蘋果提供的共享session NSURLSession *sharedSession = [NSURLSession sharedSession];
也可以透過 NSURLSessionConfiguration 自訂:
// 構造NSURLSessionConfiguration NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; // 構造NSURLSession,網絡會話; NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
Configuration 提供三種建立方式:
在後台") 時,網絡傳輸%) 交給系統獨立") 一個進程處理,即使 App 被凍結、") 出") 至崩潰,%) tải% 仍") 繼續執行。
也可以") ") ") ") 統一") ") ") ") configuration» ") ") ") "
// 構造NSURLSessionConfiguration NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; //設置請求超時為10秒鐘 configuration.timeoutIntervalForRequest = 10; //在蜂窩網絡情況下是否繼續請求(上傳或下載) configuration.allowsCellularAccess = NO; //配置請求頭 configuration.HTTPAdditionalHeaders =@{@"Content-Encoding":@"gzip"}; 4)建立 Task 並執行
// 構造NSURLSessionTask,會話任務; NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { // 請求失敗,打印錯誤信息 if (error) { NSLog(@"get error :%@",error.localizedDescription); } //請求成功,解析數據 else { // JSON數據格式解析 id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error]; // 判斷是否解析成功 if (error) { NSLog(@"get error :%@",error.localizedDescription); }else { NSLog(@"get success :%@",object); // 解析成功,處理數據,通過GCD獲取主隊列,在主線程中刷新界面。 dispatch_async(dispatch_get_main_queue(), ^{ // 刷新界面.... }); } } }];為適應不同場景,iOS 提供了幾種 Task 類型:
Task 的三個") ") ") 方法:
其他請求示例
1)POST 請求
// 1、創建URL資源地址 NSURL *url = [NSURL URLWithString:@"https://api.nohttp.net/postBody"]; // 2、創建Reuest請求 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // 3、配置Request // 設置請求超時 [request setTimeoutInterval:10.0]; // 設置請求方法 [request setHTTPMethod:@"POST"]; // 設置頭部參數 [request addValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"]; // 4、構造請求參數 // 4.1、創建字典參數,將參數放入字典中,可防止程序員在主觀意識上犯錯誤,即參數寫錯。 NSDictionary *parametersDict = @{@"name":@"yanzhenjie",@"pwd":@"123"}; // 4.2、遍歷字典,以“key=value&”的方式創建參數字符串。 NSMutableString *parameterString = [[NSMutableString alloc]init]; int pos =0; for (NSString *key in parametersDict.allKeys) { // 拼接字符串 [parameterString appendFormat:@"%@=%@", key, parametersDict[key]]; if(pos2)附帶表單參數的檔案上傳
NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0]; NSTimeInterval a=[dat timeIntervalSince1970]; NSString* fileName = [NSString stringWithFormat:@"file_%0.f.txt", a]; [FileUtils writeDataToFile:fileName data:[@"upload_file_to_server" dataUsingEncoding:NSUTF8StringEncoding]]; // 以流的方式上傳,大小理論上不受限制,但應注意時間 // 1、創建URL資源地址 NSURL *url = [NSURL URLWithString:@"https://api.nohttp.net/upload"]; // 2、創建Reuest請求 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // 3、配置Request //設置Body值方法二,這種方法比較原始,不常用,不過可以用來上傳參數和文件 NSString *BOUNDARY = @"whoislcj";//表單分界線 可以自定義任意值 [request setValue:[@"multipart/form-data; boundary=" stringByAppendingString:BOUNDARY] forHTTPHeaderField:@"Content-Type"]; // 文件上傳使用post [request setHTTPMethod:@"POST"]; // 設置請求超時 [request setTimeoutInterval:30.0f]; //用於存放二進制數據流 NSMutableData *body = [NSMutableData data]; //追加一個普通表單參數 name=yanzhenjie NSString *nameParam = [NSString stringWithFormat:@"--%@\r\nContent-Disposition: form-data; name=\"%@\"\r\n\r\n%@\r\n",BOUNDARY,@"name",@"yanzhenjie",nil]; [body appendData:[nameParam dataUsingEncoding:NSUTF8StringEncoding]]; //追加一個普通表單參數 pwd=123 NSString *pwdParam = [NSString stringWithFormat:@"--%@\r\nContent-Disposition: form-data; name=\"%@\"\r\n\r\n%@\r\n",BOUNDARY,@"pwd",@"123",nil]; [body appendData:[pwdParam dataUsingEncoding:NSUTF8StringEncoding]]; //追加一個文件表單參數 // Content-Disposition: form-data; name="服務器端需要知道的名字"; filename="服務器端這個傳上來的文件名" // Content-Type: application/octet-stream --根據不同的文件類型選擇不同的值 NSString *file = [NSString stringWithFormat:@"--%@\r\nContent-Disposition: form-data; name=\"%@\";filename=\"%@\"\r\nContent-Type: application/octet-stream\r\n\r\n",BOUNDARY,@"headUrl",fileName,nil]; [body appendData:[file dataUsingEncoding:NSUTF8StringEncoding]]; //獲取file路徑 NSString *filePath =[FileUtils getFilePath:fileName]; NSData *data =[NSData dataWithContentsOfFile:filePath]; //追加文件二進制數據 [body appendData:data]; [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; //結束分割線 NSString *endString = [NSString stringWithFormat:@"--%@--",BOUNDARY]; [body appendData:[endString dataUsingEncoding:NSUTF8StringEncoding]]; // 創建會話 NSURLSession *session = [NSURLSession sharedSession]; // 3.開始上傳 request的body data將被忽略,而由fromData提供 NSURLSessionUploadTask *uploadTask= [session uploadTaskWithRequest:request fromData:body completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { if (error) { NSLog(@"upload error:%@",error); } else { NSLog(@"upload success:%@", [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error]); dispatch_async(dispatch_get_main_queue(), ^{ // 刷新界面... }); } }]; //執行任務 [uploadTask resume]; 3)檔案下載
// 創建url NSString *urlStr =@"https://images2015.cnblogs.com/blog/950883/201701/950883-20170105104233581-62069155.png"; NSURL *Url = [NSURL URLWithString:urlStr]; // 創建請求 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:Url]; // 設置請求超時 [request setTimeoutInterval:30.0]; // 創建會話 NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDownloadTask *downLoadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) { if (!error) { NSLog(@"download sucess : %@", location); NSData *data=[NSData dataWithContentsOfURL:location]; UIImage *image=[UIImage imageWithData:data]; dispatch_async(dispatch_get_main_queue(), ^{ // 刷新界面... UIImageView *imageView =[[UIImageView alloc]init]; imageView.image=image; [self.view addSubview:imageView]; [imageView mas_makeConstraints:^(MASConstraintMaker *make) { make.center.equalTo(self.view); make.size.mas_equalTo(CGSizeMake(300, 300)); }]; }); } else { NSLog(@"download error : %@", error.localizedDescription); } }]; //啟動任務 [downLoadTask resume]; 總結:
今天梳理了 iOS 底層如何實作網絡請求。真正開發時當然還是得")
靠優秀的第三方開源框架")
")
")
"),")
"),")
"),")
"