这篇文章主要介绍了IOS 城市定位详解及简单实例的相关资料,需要的朋友可以参考下
IOS 城市定位
前言:
获取经纬度并且转换成城市
iOS8定位失败解决
获取中文城市
1、建立简单的项目, 导入CoreLoation.framework
:
2、在Info.plist
中加上NSLocationAlwaysUsageDescription
值为AlwaysLocation
:
3、使用CLLocationManager
对象进行定位:
_locationManger = [[CLLocationManager alloc] init];
_locationManger.delegate = self;
[_locationManger requestAlwaysAuthorization];//iOS8需要加上,不然定位失败
_locationManger.desiredAccuracy = kCLLocationAccuracyBest; //最精确模式
_locationManger.distanceFilter = 100.0f; //至少10米才请求一次数据
[_locationManger startUpdatingLocation]; //开始定位
4、在CLLocationManagerDelegate
代理方法(iOS8)中获取定位信息并且转换成中文城市:
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
NSLog(@"定位失败");
[_locationManger stopUpdatingLocation];//关闭定位
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
NSLog(@"定位成功");
[_locationManger stopUpdatingLocation];//关闭定位
CLLocation *newLocation = locations[0];
NSLog(@"%@",[NSString stringWithFormat:@"经度:%3.5f\n纬度:%3.5f",newLocation.coordinate.latitude, newLocation.coordinate.longitude]);
// 保存 设备 的当前语言
NSMutableArray *userDefaultLanguages = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
// 强制 成 简体中文
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"zh-hans", nil nil] forKey:@"AppleLanguages"];
CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
for (CLPlacemark * placemark in placemarks) {
NSDictionary *test = [placemark addressDictionary];
// Country(国家) State(城市) SubLocality(区)
NSLog(@"%@", [test objectForKey:@"State"]);
// 当前设备 在强制将城市改成 简体中文 后再还原之前的语言
[[NSUserDefaults standardUserDefaults] setObject:userDefaultLanguages forKey:@"AppleLanguages"];
}
}];
}
首次启动时,会提示是否开启定位并显示NSLocationAlwaysUsageDescription
的值:
其中字典test的具体内容是:
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!