post异步session
NSURL *url = [NSURL URLWithString:URL_PORT1];//1.创建URL对象
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];2.创建请求对象
[request setHTTPMethod:@”post”];//2.1
NSData *tempData = [URL_PORT2 dataUsingEncoding:NSUTF8StringEncoding];//参数转化
[request setHTTPBody:tempData];
NSURLSession *session = [NSURLSession sharedSession];//3.建立会话
session支持三种类型的任务
NSURLSessionDataTask;//(加载数据)
NSURLSessionDownloadTask;//(下载)
NSURLSessionUploadTask;//(上传)
NSLog(@”%d”,[[NSThread currentThread]isMainThread]);
__weak typeof (self)temp = self;//判断是否是子线程 1是子线程,0不是主线程
NSURLSessionDataTask task = [session dataTaskWithRequest:request completionHandler:^(NSData _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; //解析
NSLog(@”%@”,dic);
NSLog(@”—%d—”,[[NSThread currentThread]isMainThread]);
dispatch_async(dispatch_get_main_queue(), ^{//回到主线程(刷新数据)
[temp.tableView reloadData]; //相当于tableView的刷新数据
});
}];
[task resume];//4.启动任务
}
get异步session
NSURL *url = [NSURL URLWithString:BASE_URL];//1.创建url对象
NSURLSession *session = [NSURLSession sharedSession];//2.创建session对象
NSURLSessionDataTask task = [session dataTaskWithURL:url completionHandler:^(NSData _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {//3.创建task (该方法内部做了处理,默认使用get,直接传递Url即可);
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
dispatch_async(dispatch_get_main_queue(), ^{
});
[task resume];
}