参考链接
https://www.jianshu.com/p/5bbfefc50089
https://www.jianshu.com/p/d11b495b7674
结构
image
image
image
使用
/// 向网络请求数据
- (void)NSURLSessionTest {
// 1.创建url
// 请求一个网页
NSString *urlString = @"http://www.cnblogs.com/mddblog/p/5215453.html";
// 一些特殊字符编码
urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString:urlString];
// 2.创建请求 并:设置缓存策略为每次都从网络加载 超时时间30秒
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];
// 3.采用苹果提供的共享session
NSURLSession *sharedSession = [NSURLSession sharedSession];
// 4.由系统直接返回一个dataTask任务
NSURLSessionDataTask *dataTask = [sharedSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// 网络请求完成之后就会执行,NSURLSession自动实现多线程
NSLog(@"%@",[NSThread currentThread]);
if (data && (error == nil)) {
// 网络访问成功
NSLog(@"data=%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
} else {
// 网络访问失败
NSLog(@"error=%@",error);
}
}];
// 5.每一个任务默认都是挂起的,需要调用 resume 方法
[dataTask resume];
}