@interface ViewController ()<NSURLSessionDataDelegate>
//创建数据容器,接收返回数据
@property (nonatomic, strong) NSMutableData *data;
@end
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self dataTask];
}
-(void)dataTask {
// 1创建请求地址 读者自行更换URL
NSURL *url = [NSURL URLWithString:@"https://api.seniverse.com/v3/weather/now.json?key=????&location=zunyi&language=zh-Hans&unit=c"];
// 2创建请求类
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 3创建会话
/*
默认
NSURLSessionConfiguration *defaultSessionConfiguration;
无痕浏览,不存储任何信息
NSURLSessionConfiguration *ephemeralSessionConfiguration;
后台下载
+ (NSURLSessionConfiguration *)backgroundSessionConfigurationWithIdentifier:(NSString *)identifier
delegateQueue:表示协议方法在哪个线程中执行
*/
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
// 4根据会话创建任务
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request];
//5启动任务
[dataTask resume];
}
#pragma mark --协议方法
//接收到服务器响应
-(void)URLSession:(NSURLSession *)session dataTask:(nonnull NSURLSessionDataTask *)dataTask didReceiveResponse:(nonnull NSURLResponse *)response completionHandler:(nonnull void (^)(NSURLSessionResponseDisposition))completionHandler
{
NSLog(@"didReceiveResponse");
if (self.data == nil) {
self.data = [[NSMutableData alloc] init];
}else {
self.data.length = 0;
}
/*
NSURLSessionResponseCancel = 0 默认 请求之后不接收服务器的数据
NSURLSessionResponseAllow = 1 允许接收服务器的数据
NSURLSessionResponseBecomeDownload = 2 转成下载任务
NSURLSessionResponseBecomeStream = 3 转成流
*/
completionHandler (NSURLSessionResponseAllow);
}
//接收到数据,该方法会被调用多次
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
NSLog(@"didReceiveData");
[self.data appendData:data];
}
//数据请求完成或者请求出现错误调用的方法
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
NSLog(@"didCompletWithError");
if (error == nil) {
//解析数据
id objc = [NSJSONSerialization JSONObjectWithData:self.data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"--%@--",objc);
}
}