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];
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];
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];
// 使用這種方式取消下載能夠獲得未來用來恢復的數據,保存起來 [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];
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]);}];
//使用代理方法須要設置代理,可是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]; }
- (void)suspend; - (void)resume; - (void)cancel;
+ (NSURLSessionConfiguration *)defaultSessionConfiguration; + (NSURLSessionConfiguration *)ephemeralSessionConfiguration; + (NSURLSessionConfiguration *)backgroundSessionConfigurationWithIdentifier:(NSString *)identifier
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; // 超時時間 config.timeoutIntervalForRequest = 10; // 是否容許使用蜂窩網絡(後臺傳輸不適用) config.allowsCellularAccess = YES; // 還有不少能夠設置的屬性
特別說明,本文是對簡書《使用NSURLSession》的學習與記錄,在使用方面作了一些調研和實驗。json