使用NSURLSession的步驟:
第一步 通過NSURLSession的實例創建task
第二步 執行task
- (void)NSURLSessionRequest
{
//創建URL
NSString *URLPath = @"https://xxxx";
NSURLSession *sharedSession = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [sharedSession dataTaskWithURL:[NSURL URLWithString:URLPath] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSDictionary *contentDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSError *merror = nil;
self.successModel = [MTLJSONAdapter modelOfClass:[AWESuccessModel class] fromJSONDictionary:contentDictionary error:&merror]; // 2
self.postsModels = self.successModel.successInfo.posts;
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];//注意位置
});
self.heightCaches = [NSMutableArray array];
for (AWEPostsModel *postModel in self.postsModels) {
AWEPostsModel *model = [[AWEPostsModel alloc] init];
model.content = postModel.content;
model.likesName = postModel.likesName;
CGFloat postModelHeight = [AWELabCell heightWithModel:model];
[self.heightCaches addObject:[NSNumber numberWithFloat:postModelHeight]];
}
if (error) {
NSLog(@"error---->%@",error);
} else {
//NSLog(@"model--->%@",model);
}
}];
//每個任務默認都是掛起的,需要調用resume方法
[dataTask resume];
}
NSURLSessionTask可以簡單的理解爲任務:如數據請求任務(NSURLSessionDataTask),下載任務(NSURLSessionDownloadTask),上傳任務(NSURLSessionUploadTask)。
NSURLSessionDataTask
這個可以處理和數據相關的任務,也可以勝任downloadTask和uploadTask的工作。
簡單GET請求
// 快捷方式獲得session對象
NSURLSession *session = [NSURLSession sharedSession];
NSURL *url = [NSURL URLWithString:@"http://www.daka.com/login?username=daka&pwd=123"];
// 通過URL初始化task,在block內部可以直接對返回的數據進行處理
NSURLSessionTask *task = [session dataTaskWithURL:url
completionHandler:^(NSData *data, NSURLResponse *response, NSError error) {
NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}];
// 啓動任務
[task resume];
tips:
所有類型的task都要調用resume方法纔會開始進行請求。
簡單POST請求
post和get的區別就在於request,所以使用session的post請求和get請求的過程相同,區別就在於對requestde 處理。
NSURL *url = [NSURL URLWithString:@"http://www.daka.com/login"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
request.HTTPBody = [@"username=daka&pwd=123" dataUsingEncoding:NSUTF8StringEncoding];
NSURLSession *session = [NSURLSession sharedSession];
// 由於要先對request先行處理,我們通過request初始化task
NSURLSessionTask *task = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]); }];
[task resume];
NSURLSessionDownloadTask
簡單下載
SURLSession *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];
NSURLSessionUploadTask
[self.session uploadTaskWithRequest:request
fromData:body
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"-------%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}];
斷點下載
// 使用這種方式取消下載可以得到將來用來恢復的數據,保存起來
[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];