NSURLSession
在2013年, 蘋(píng)果解開(kāi)了NSURLSession的面紗, 作為NSURLConnection的繼承者, 比較NSURLConnection, NSURLSession提供了配置會(huì)話緩存,協(xié)議,cookie和證書(shū)的能力, 這使得網(wǎng)絡(luò)架構(gòu)和應(yīng)用程序可以獨(dú)立工作, 互不干擾, 另外, NSURLSession另一個(gè)重要的部分是會(huì)話任務(wù), 它負(fù)責(zé)加載數(shù)據(jù), 在客戶端和服務(wù)器端進(jìn)行文件的上傳下載.
-
NSURLSession
- NSURLConnection主要任務(wù):
- 獲取數(shù)據(jù)(JSON, XML),
- 文件上傳.
- 文件下載.
- NSURLSession中, 三個(gè)人物分別由以下的抽象類來(lái)完成.
- NSURLSessionData
- NSURLSessionUploadTask,
- NSURLSessionDownloadTask,
這三個(gè)類都是 NSURLSessionTask這個(gè)抽象類的子類, 相比直接使用NSURLConnection, NSURLSessionTask支持任務(wù)的暫停、取消和恢復(fù)瘩燥,并且默認(rèn)任務(wù)運(yùn)行在其他非主線程中.
- NSURLConnection主要任務(wù):
-
數(shù)據(jù)請(qǐng)求
NSURLSessionDataTask實(shí)現(xiàn)流程與NSURLConnection的靜態(tài)方法類似, 代碼如下: -(void)loadJsonData{ 1.創(chuàng)建url NSString *urlStr=[NSString stringWithFormat:@"http://192.168.1.208/ViewStatus.aspx?userName=%@&password=%@",@"KenshinCui",@"123"]; urlStr =[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url=[NSURL URLWithString:urlStr]; 2.創(chuàng)建請(qǐng)求 NSURLRequest *request=[NSURLRequest requestWithURL:url]; 3.創(chuàng)建會(huì)話(這里使用了一個(gè)全局會(huì)話)并且啟動(dòng)任務(wù) NSURLSession *session=[NSURLSession sharedSession]; // 從會(huì)話創(chuàng)建任務(wù) NSURLSessionDataTask *dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (!error) { NSString *dataStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@",dataStr); }else{ NSLog(@"error is :%@",error.localizedDescription); } }]; [dataTask resume];//恢復(fù)線程子檀,啟動(dòng)任務(wù) }
-
如何使用NSURLSessionUploadTask實(shí)現(xiàn)文件上傳, 這里有幾個(gè)方法
#pragma mark 取得mime types -(NSString *)getMIMETypes:(NSString *)fileName{ return @"image/jpg"; } #pragma mark 取得數(shù)據(jù)體 -(NSData *)getHttpBody:(NSString *)fileName{ NSString *boundary=@"KenshinCui"; NSMutableData *dataM=[NSMutableData data]; NSString *strTop=[NSString stringWithFormat:@"--%@\nContent- Disposition: form-data; name=\"file1\"; filename=\"%@\"\nContent-Type: %@\n\n",boundary,fileName,[self getMIMETypes:fileName]]; NSString *strBottom=[NSString stringWithFormat:@"\n--%@--",boundary]; NSString *filePath=[[NSBundle mainBundle] pathForResource:fileName ofType:nil]; NSData *fileData=[NSData dataWithContentsOfFile:filePath]; [dataM appendData:[strTop dataUsingEncoding:NSUTF8StringEncoding]]; [dataM appendData:fileData]; [dataM appendData:[strBottom dataUsingEncoding:NSUTF8StringEncoding]]; return dataM; } #pragma mark 上傳文件 -(void)uploadFile{ NSString *fileName=@"pic.jpg"; //1.創(chuàng)建url NSString *urlStr=@"http://192.168.1.208/FileUpload.aspx"; urlStr =[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url=[NSURL URLWithString:urlStr]; //2.創(chuàng)建請(qǐng)求 NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url]; request.HTTPMethod=@"POST"; //3.構(gòu)建數(shù)據(jù) NSString *path=[[NSBundle mainBundle] pathForResource:fileName ofType:nil]; NSData *data=[self getHttpBody:fileName]; request.HTTPBody=data; [request setValue:[NSString stringWithFormat:@"%lu",(unsigned long)data.length] forHTTPHeaderField:@"Content-Length"]; [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",@"KenshinCui"] forHTTPHeaderField:@"Content-Type"]; //4.創(chuàng)建會(huì)話 NSURLSession *session=[NSURLSession sharedSession]; NSURLSessionUploadTask *uploadTask=[session uploadTaskWithRequest:request fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (!error) { NSString *dataStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@",dataStr); }else{ NSLog(@"error is :%@",error.localizedDescription); } }]; [uploadTask resume]; }
-
文件下載
使用NSURLSessionDownloadTask下載文件的過(guò)程與前面差不多, 需要注意的是文件下載文件之后會(huì)自動(dòng)保存到一個(gè)臨時(shí)目錄. 需要開(kāi)發(fā)人員自己講文件重新放到其他指定的目錄下.-(void)downloadFile{ //1.創(chuàng)建url NSString *fileName=@"1.jpg"; NSString *urlStr=[NSString stringWithFormat: @"http://192.168.1.208/FileDownload.aspx?file=%@",fileName]; urlStr =[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url=[NSURL URLWithString:urlStr]; //2.創(chuàng)建請(qǐng)求 requestWithURL:url]; //3.創(chuàng)建會(huì)話(這里使用了一個(gè)全局會(huì)話)并且啟動(dòng)任務(wù) NSURLSession *session=[NSURLSession sharedSession]; NSURLSessionDownloadTask *downloadTask=[session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) { if (!error) { //注意location是下載后的臨時(shí)保存路徑,需要將它移動(dòng)到需要保存的位置 NSError *saveError; NSString *cachePath=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; NSString *savePath=[cachePath stringByAppendingPathComponent:fileName]; NSLog(@"%@",savePath); NSURL *saveUrl=[NSURL fileURLWithPath:savePath]; [[NSFileManager defaultManager] copyItemAtURL:location toURL:saveUrl error:&saveError]; if (!saveError) { NSLog(@"save sucess."); }else{ NSLog(@"error is :%@",saveError.localizedDescription); } }else{ NSLog(@"error is :%@",error.localizedDescription); } }]; [downloadTask resume]; }
-
會(huì)話,(session 翻譯成會(huì)話不太好)
NSURLConnection通過(guò)全局狀態(tài)管理cookies, 認(rèn)證信息等公共資源, 這樣如果遇到兩個(gè)鏈接需要使用不同的資源配置情況時(shí),就無(wú)法解決了, 但是這個(gè)問(wèn)題在NSURLSession中得到了結(jié)局. NSURLSession同事對(duì)應(yīng)著多個(gè)鏈接, 會(huì)話通過(guò)工廠方法來(lái)創(chuàng)建, 同一個(gè)會(huì)話使用相同的狀態(tài)信息. NSURLSession支持進(jìn)程三種會(huì)話:- defaultSessionConfiguration:進(jìn)程內(nèi)會(huì)話(默認(rèn)會(huì)話)辩越,用硬盤(pán)來(lái)緩存數(shù)據(jù)。
- ephemeralSessionConfiguration:臨時(shí)的進(jìn)程內(nèi)會(huì)話(內(nèi)存)埃跷,不會(huì)將cookie、緩存儲(chǔ)存到本地,只會(huì)放到內(nèi)存中典唇,當(dāng)應(yīng)用程序退出后數(shù)據(jù)也會(huì)消失。
- backgroundSessionConfiguration:后臺(tái)會(huì)話胯府,相比默認(rèn)會(huì)話介衔,該會(huì)話會(huì)在后臺(tái)開(kāi)啟一個(gè)線程進(jìn)行網(wǎng)絡(luò)數(shù)據(jù)處理。