ios关于天气预报接口
第三方“聚合数据”,天气预报每天免费调用100次,需要申请,需要实名认证。
在获取城市名称后,可根据城市名称获取该城市的天气信息。
currentCity设置为全局
NSString *url = [NSString stringWithFormat:@"https://op.juhe.cn/onebox/weather/query?cityname=%@&key=你申请的key",currentCity];
//NSLog(url);
NSString *str = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url1 = [NSURL URLWithString:str];
NSURLRequest *urlR = [NSURLRequest requestWithURL:url1];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:urlR completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSString *rec = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:[rec dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil];
// NSLog(@"weather dic is %@", dic);
NSDictionary *resultDic = [dic objectForKey:@"result"];
// NSLog(@"resultArr is %@",resultDic);
NSDictionary *dataDic = [resultDic objectForKey:@"data"];
//NSLog(@"dataArr is %@",dataDic);
NSArray *weatherArr = [dataDic objectForKey:@"weather"];
//NSLog(@"weather is %@", weatherDic);
NSArray *realtimeWeather = [dataDic objectForKey:@"realtime"];
NSLog(@"realtimeWeather is %@",realtimeWeather);
//回到主线程刷新页面
dispatch_async(dispatch_get_main_queue(), ^{
//NSLog(@"weatherDic is %@");
NSLog(@"-------------------------------");
NSLog(@"weatherArr[0] is %@",weatherArr[0]);
NSLog(@"地点:%@",currentCity);
NSString *date = [weatherArr[0] objectForKey:@"date"]; //日期
NSLog(@"日期:%@",date);
NSDictionary *info = [weatherArr[0] objectForKey:@"info"];
NSArray *day = [info objectForKey:@"day"];
NSArray *night = [info objectForKey:@"night"];
NSLog(@"温度%@-%@",night[2],day[2]);
NSLog(@"天气:%@",day[1]);
NSLog(@"风向风力:%@\%@",day[3],day[4]);
NSString *week = [weatherArr[0] objectForKey:@"week"];
NSLog(@"星期: %@",week);
});
}];
[dataTask resume];
//NSLog(@"rgc = %@",[location.rgcData description]);//详细信息
}