还是觉得网络请求有点神奇吧
然后请求好数据后
如何去使用花了点时间
其实最简单的方法就是一个字典
一层一层得到目标数据就行
- (void)createURL {
//1.创建请求地址
NSString *urlString = [NSString stringWithFormat:@"https://free-api.heweather.net/s6/weather?location=%@&key=715f3ed25f7148ceadaacd5aceaded72", [_mainViewCityArray[_mainViewCityArray.count - 1] substringWithRange:(NSMakeRange(0, 2))]];
//处理字符
//返回由接收器生成的新字符串,方法是用百分比编码字符替换指定集之外的所有字符。
//URLQueryAllowedCharacterSet:返回查询URL组件中允许的字符集。
urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//创建URL
NSURL *url = [NSURL URLWithString:urlString];
//2.创建请求类
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//3.创建会话
//delegateQueue 表示协议方法在哪个线程中执行
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
//4.根据会话创建任务
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request];
//5.启动任务
[dataTask resume];
}
//接收服务器的响应
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
NSLog(@"didReceiveResponse");
if(self.data == nil){
self.data = [[NSMutableData alloc] init];
} else {
//length:可变数据对象中包含的字节数。
self.data.length = 0;
}
//允许接收数据
//不可少
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(@"didCompleteWithError");
if (error == nil) {
//解析数据步骤
//字典
NSDictionary *secondDictionary = [NSJSONSerialization JSONObjectWithData:_data options:kNilOptions error:nil];
NSLog(@"时间%@", [secondDictionary[@"HeWeather6"][0][@"update"][@"loc"] substringWithRange:(NSMakeRange(10, 6))]);
NSLog(@"温度%@", secondDictionary[@"HeWeather6"][0][@"now"][@"tmp"]);
[_timeArray addObject:[secondDictionary[@"HeWeather6"][0][@"update"][@"loc"] substringWithRange:(NSMakeRange(10, 6))]];
[_tempArray addObject:[secondDictionary[@"HeWeather6"][0][@"now"][@"tmp"] stringByAppendingString:@"℃"]];
NSLog(@"error = %@", error);
}
//addOperationWithBlock:在操作中包装指定的块并将其添加到接收器。
//对UI的操作必须回归到主线程
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self->_tableView reloadData];
}];
}