iOS - NSURLSession的简单使用

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];
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值