使用NSURLSession来进行HTTP请求一共需要5个步骤
1,实例化一个NSURLRequest或者NSMutableURLRequest,设置URL
2,通过shareSession方法获取URLSession
3,在session上调用dataTastWithRequest:CompletionHandler: 方法返回一个NSURLSessionDataTask
4,向dataTask发送消息 ,resume开始执行任务
5,在completion中将返回的数据编码,返回数据
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[[NSURL alloc] initWithString:@"https://www.baidu.com/"]];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", dataStr);
}];
[task resume];
本文介绍了使用NSURLSession发起HTTP请求的五个步骤:实例化请求、获取会话、创建数据任务、启动任务及处理响应数据。提供了完整的代码示例。
498

被折叠的 条评论
为什么被折叠?



