NSURLSession:
今天主要写一个小的程序示例,来说明NSURLSession的使用
流程:
1、创建session
2、使用session创建task
3、使用task启动任务
// 创建session对象
NSURLSession *session = [NSURLSession sharedSession];
// 创建任务usr
NSURLSessionDataTask *task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://image.baidu.com/search/down?tn=download&ipn=dwnl&word=download&ie=utf8&fr=result&url=http%3A%2F%2Fpic74.nipic.com%2Ffile%2F20150728%2F18138004_201107753000_2.jpg&thumburl=http%3A%2F%2Fimg2.imgtn.bdimg.com%2Fit%2Fu%3D769208822%2C464174748%26fm%3D21%26gp%3D0.jpg"]] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"hello");
[data writeToFile:@"/Users/usr/Downloads/cat.jpg" atomically:NO];
}];
[task resume];// 执行任务
// 解析:
1、会话类型有三种,其他创建方式可以指定,此处为defaultSession;
[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
在configuration中可以设置session类型,超时等参数;
2、任务类型有三种:
NSURLSessionDataTask/ 上传和下载,默认的执行方式为GET,可手动改为POST
NSURLSessionDownloadTask/下载,下载的数据默认在tmp中,需移到cache中下片来讲
NSURLSessionUploadTask 上传
ios9以后执行http协议会报错:
App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.
解决方案:
在info.plist文件中添加:App Transport Security Settings类型为NSDictionary,然后往改Dictionary中添加Boolean变量Allow Arbitrary Loads,value为YES;