这一周接触了网络请求,但也只是简单的了解。
以下为天气预报项目中城市搜索联想。
//对textField实时监听
- (void)textFieldDidChange:(UITextField *)textField {
//设置请求地址
NSString *str = [NSString stringWithFormat:@"https://geoapi.heweather.net/v2/city/lookup?location=%@&key=c2155cc73435455ebc84b8fc952d8b26", textField.text];
NSURL *url = [NSURL URLWithString:str];
//创建请求类
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//创建会话
//delegateQueue表示协议方法在哪个线程中执行
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
//根据会话创建任务
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request];
//启动任务
[dataTask resume];
}
//接收到服务器响应
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
NSLog(@"1");
if(_data == nil) {
_data = [[NSMutableData alloc] init];
} else {
_data.length = 0;
}
//允许接收服务器的数据
completionHandler(NSURLSessionResponseAllow);
}
//接收到数据 该方法会被调用多次
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
NSLog(@"2");
//拼接data
[_data appendData:data];
}
//数据请求完成或请求出现错误调用的方法
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
NSLog(@"3");
//请求成功
if(error == nil) {
//解析数据
id dictionary = [NSJSONSerialization JSONObjectWithData:_data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"-------%@", dictionary);
NSArray *cityArr = [dictionary objectForKey:@"location"] ;
_cityArr = [[NSMutableArray alloc] init];
_array = [[NSMutableArray alloc] init];
_idArr = [[NSMutableArray alloc] init];
for(int i = 0; i < cityArr.count; i++) {
NSString *cityStr = [NSString stringWithFormat:@"%@", dictionary[@"location"][i][@"name"]];
NSString *provinceStr = [NSString stringWithFormat:@"%@", dictionary[@"location"][i][@"adm1"]];
NSString *idStr = [NSString stringWithString:dictionary[@"location"][i][@"id"]];
NSString *string = [NSString stringWithFormat:@"%@, %@", cityStr, provinceStr];
[_cityArr addObject:string];
[_array addObject:cityStr];
[_idArr addObject:idStr];
}
[_tableView reloadData];
}
}