美文网首页
通过系统定位获取天气信息

通过系统定位获取天气信息

作者: 岳阳_ | 来源:发表于2016-11-03 11:30 被阅读121次

首先,需要通过系统方法获取当前经纬度

引入头文件 #import <coreLocation/CoreLocation.h>

创建manager对象,用来获取当前位置

@property (strong, nonatomic)CLLocationManager *locationManager;

然后,写一个实例方法,来统一获取定位、温度

#pragma mark --定位&温度

- (void)locationAndTemperature{

// 初始化位置管理器

if (![CLLocationManager locationServicesEnabled])

{

//定位未开启,温度无法显示 (笔者并未完善,读者此处可以根据需求进行修改)

}

else

{

_locationManager = [[CLLocationManager alloc] init];

_locationManager.delegate = self;

[self.locationManager requestWhenInUseAuthorization];

[_locationManager startUpdatingLocation];

}

}

开始系统定位以后,系统会以非常高的频率执行更新定位方法

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray*)locations{

此处的locations 就是当前定位的数组,里面存的是CLLocation 类型的位置信息 包含经纬度

此时,笔者使用的是与苹果系统相同的天气API,需要通过城市名获取当前天气信息的JSON文件,因此,此时可以通过系统的反向地理编码获取当前经纬度所在的城市。

// 获取当前所在的城市名

CLGeocoder *geocoder = [[CLGeocoder alloc] init];

for (CLLocation *loca in _locations) {

[geocoder reverseGeocodeLocation:loca completionHandler:^(NSArray *array, NSError *error){

if (array.count > 0)

{

CLPlacemark *placemark = [array objectAtIndex:0];

NSString *city = placemark.locality;

NSString *city1 = [city stringByReplacingCharactersInRange:NSMakeRange(city.length-1,1) withString:@""];

//更改为英文 并调用天气api进行查询 (此处调用的类方法实现,在此方法下方)同时,

[self transform:city1]用来将中文的城市名转换为英文

[WeatherService getTemperatureWithCityName:[self transform:city1] completion:^(NSError *error, id responseObject) {

if (responseObject != nil) {

[self.temperatureButton setTitle:[NSString stringWithFormat:@"%@℃",responseObject] forState:UIControlStateNormal];

;

[_locationManager stopUpdatingLocation];

}

LOG("温度%@",responseObject);

}];

}

else if (error == nil && [array count] == 0)

{

LOG("无数据返回");

}

else if (error != nil)

{

LOG("错误:%@", error);

}

}];

}

}

--此处是将中文转换为英文的方法

//将中文转换为拼音

- (NSString *)transform:(NSString *)chinese

{

if (chinese != nil) {

NSMutableString *pinyin = [chinese mutableCopy];

CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);

CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);

return [[pinyin uppercaseString] stringByReplacingOccurrencesOfString:@" " withString:@""];

}

return nil;

}

-- 此处是笔者单独封装的Weather类,用来请求数据

+ (AFHTTPRequestOperation *)getTemperatureWithCityName:(NSString *)cityName completion:(SCServiceCompletion)completion{

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

manager.responseSerializer = [AFHTTPResponseSerializer serializer];

__block NSString *temperature = @"";

AFHTTPRequestOperation * DataTask = [manager GET:[NSString stringWithFormat:@"http://api.wunderground.com/api/你的API参数/conditions/q/CA/%@.json",cityName] parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {

NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];

NSDictionary *dic1 = [dic objectForKey:@"current_observation"];

temperature = [dic1 objectForKey:@"feelslike_c"];

//        dispatch_queue_t queue = dispatch_queue_create("WEATHER", DISPATCH_QUEUE_CONCURRENT);

dispatch_async(dispatch_get_main_queue(), ^{

dispatch_async(dispatch_get_main_queue(), ^{

if (completion) {

completion(nil, temperature);

}

});

});

} failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {

}];

return DataTask;

}

此时,即可获取到手机定位所在地的体感温度

API链接地址 : http://api.wunderground.com/weather/api/d/docs?d=data/index

笔者QQ 268081059 如有不妥之处,欢迎指出

本文作者原创,如需转载,请注明出处。

相关文章

网友评论

      本文标题:通过系统定位获取天气信息

      本文链接:https://www.haomeiwen.com/subject/wkmlkttx.html