NSURLSession進行網絡請求

前言:
  蘋果的網絡請求有NSURLConnection和NSURLSession,而NSURLConnection在iOS9被宣佈棄用。AFNetworking對NSURLSession進行了封裝,另外,通常公司裏用的網絡庫,也是在NSURLSession基礎上進行封裝,使得符合本身業務的開發需求,因此,咱們頗有必要對NSURLSession的使用進行了解。本文對NSURLSession進行簡單的介紹。
 
正文:
 
1、NSURLSession簡介
 
使用NSURLSession,共分兩步:
  • 第一步 經過NSURLSession的實例建立task
  • 第二步 執行task
NSURLSessionTask的繼承關係以下圖所示:
 
 
 
2、NSURLSessionTask的使用舉例(分6種狀況)
 
(1) NSURLSessionTask進行簡單的Get請求
        NSURLSession *session = [NSURLSession sharedSession];
        NSURL *url = [NSURL URLWithString:@"https://xxx.yy.zz/check"];
        NSURLSessionTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
             if(!error){
                  NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
                  NSString *status = responseDic[@"status"];
                  if ([status isKindOfClass:[NSString class]] && [status isEqualToString:@"1"]) {
                   self.needAutoCode = YES ;
                   [self.tableView reloadData];
                  }
             }else {
                NSLog(@"%@", error);
             }
         }];
         [task resume];    
(2) NSURLSessionTask進行簡單的Post請求
    NSURL *url = [NSURL URLWithString:@"https://xxx.xxx.xx/accessToken"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    NSString *param = [NSString stringWithFormat:@"code=%@&client_secret=3QmKoBbku7&client_id=apollo&grant_type=code",self.serviceTicket];
    request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
        if((!error) && ([(NSHTTPURLResponse *)response statusCode] == 200)) {
            NSError *error0 = nil;
           NSDictionary *jsonDic =  [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error0];
            if(!error0){
                NSString *refreshToken = jsonDic[@"refresh_token"];
                NSString *accessToken = jsonDic[@"access_token"];
                //此處一些業務處理
            }else{
                NSLog(@"%@",error0.nv_message);
            }
        }else{
            NSLog(@"%@",error.nv_message);
        }
    }];
    [task resume];
(3)NSURLSessionDownloadTask進行簡單的文件下載
    NSURLSession *session = [NSURLSession sharedSession];
    NSURL *url = [NSURL URLWithString:@"http://www.daka.com/resources/image/icon.png"] ;
    NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
        // location是沙盒中tmp文件夾下的一個臨時url,文件下載後會存到這個位置,因爲tmp中的文件隨時可能被刪除,因此咱們須要本身須要把下載的文件挪到須要的地方
        NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
        // 剪切文件
        [[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:path] error:nil];
    }];
    // 啓動任務
    [task resume];
(4)斷點下載
// 使用這種方式取消下載能夠獲得未來用來恢復的數據,保存起來
[self.task cancelByProducingResumeData:^(NSData *resumeData) {
    self.resumeData = resumeData;
}];

// 因爲下載失敗致使的下載中斷會進入此協議方法,也能夠獲得用來恢復的數據
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
    // 保存恢復數據
    self.resumeData = error.userInfo[NSURLSessionDownloadTaskResumeData];
}

// 恢復下載時接過保存的恢復數據
self.task = [self.session downloadTaskWithResumeData:self.resumeData];
// 啓動任務
[self.task resume];
(5)文件上傳
    NSURLSessionUploadTask *uploadtask1 = [self.session uploadTaskWithRequest:request fromFile:fileName completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {}];
    //或者,出於安全性考慮,一般使用POST方式進行文件上傳
    NSURLSessionUploadTask *uploadtask2 = [self.session uploadTaskWithRequest:request fromData:body completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSLog(@"-------%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);}];
 
(6) 使用代理NSURLSessionDataDelegate
 
  NSURLSession提供了block方式處理返回數據的簡便方式,但若是想要在接收數據過程當中作進一步的處理,仍然能夠調用相關的協議方法.NSURLSession的代理方法分爲接收響應、接收數據、請求完成幾個階段。
  NSURLSessionDelegate的繼承關係以下圖所示:
 
 
//使用代理方法須要設置代理,可是session的delegate屬性是隻讀的,要想設置代理只能經過這種方式建立session
    self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@""]];

    // 建立任務(由於要使用代理方法,就不須要block方式的初始化了)和啓動任務
    //(1)通常請求任務
    NSURLSessionDataTask *task = [self.session dataTaskWithRequest:request];
    [task resume];
    //(2)上傳任務
    NSURLSessionUploadTask *uploadtask = [self.session uploadTaskWithRequest:request fromData:request.HTTPBody];
    [uploadtask resume];
    //(3)下載任務
    NSURLSessionDownloadTask *downloadTask = [self.session downloadTaskWithRequest:request];
    [downloadTask resume];

//對應的代理方法以下:
# pragma mark NSURLSessionTaskDelegate // 請求成功或者失敗(若是失敗,error有值) - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { // 請求完成,成功或者失敗的處理 if (self.completion) { NSData *data = nil; if (self.receivedData) { data = [self.receivedData copy]; self.receivedData = nil; } self.completion(self.cmd, task.response, data, error,error); } [self.session invalidateAndCancel]; } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend { if (self.uploadBlock) { int64_t totalUnitCount = totalBytesExpectedToSend; if(totalUnitCount == NSURLSessionTransferSizeUnknown) { NSString *contentLength = [task.originalRequest valueForHTTPHeaderField:@"Content-Length"]; if(contentLength) { totalUnitCount = (int64_t) [contentLength longLongValue]; } } NSInteger totalBytesSentInt = [[NSNumber numberWithLongLong:totalBytesSent] integerValue]; NSInteger totalUnitCountInt = [[NSNumber numberWithLongLong:totalUnitCount] integerValue]; self.uploadBlock(totalBytesSentInt,totalUnitCountInt); } } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest * __nullable))completionHandler{ //禁止302 301重定向 completionHandler(nil); } # pragma mark NSURLSessionDataDelegate // 接收到服務器的響應 - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler { // 容許處理服務器的響應,纔會繼續接收服務器返回的數據 completionHandler(NSURLSessionResponseAllow); } // 接收到服務器的數據(可能調用屢次) - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { // 處理每次接收的數據 [self.receivedData appendData:data]; } # pragma mark NSURLSessionDownloadDelegate // 每次寫入調用(會調用屢次) - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { if (self.downloadBlock) { NSInteger bytesWrittenInt = [[NSNumber numberWithLongLong:totalBytesWritten] integerValue]; NSInteger totalBytesExpectedToWriteInt = [[NSNumber numberWithLongLong:totalBytesExpectedToWrite] integerValue]; self.downloadBlock(bytesWrittenInt,totalBytesExpectedToWriteInt); } //另外, 可在這裏經過已寫入的長度和總長度算出下載進度 CGFloat progress = 1.0 * totalBytesWritten / totalBytesExpectedToWrite; NSLog(@"%f",progress); } // 下載完成調用 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location { self.receivedData = [[NSData dataWithContentsOfURL:location.filePathURL] mutableCopy]; }
 
3、其餘
 
task擁有下面三個方法:
- (void)suspend;
- (void)resume;
- (void)cancel;
suspend可讓當前的任務暫停;
resume方法不只能夠啓動任務,還能夠喚醒suspend狀態的任務;
cancel方法能夠取消當前的任務,你也能夠向處於suspend狀態的任務發送cancel消息,任務若是被取消便不能再恢復到以前的狀態.
 
NSURLSessionConfiguration配置有三種類型:
+ (NSURLSessionConfiguration *)defaultSessionConfiguration;
+ (NSURLSessionConfiguration *)ephemeralSessionConfiguration;
+ (NSURLSessionConfiguration *)backgroundSessionConfigurationWithIdentifier:(NSString *)identifier
默認的配置會將緩存存儲在磁盤上,第二種瞬時會話模式不會建立持久性存儲的緩存,第三種後臺會話模式容許程序在後臺進行上傳下載工做.
 
配置能夠設置session的一些配置信息,以下舉例:
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
// 超時時間
config.timeoutIntervalForRequest = 10;
// 是否容許使用蜂窩網絡(後臺傳輸不適用)
config.allowsCellularAccess = YES;
// 還有不少能夠設置的屬性

 

特別說明,本文是對簡書《使用NSURLSession》的學習與記錄,在使用方面作了一些調研和實驗。json

相關文章
相關標籤/搜索