iOS_城市定位一二事

image

致谢:

获取经纬度并且转换成城市

iOS8定位失败解决

获取中文城市

1、建立简单的项目, 导入CoreLoation.framework:

image

2、在Info.plist中加上NSLocationAlwaysUsageDescription值为AlwaysLocation

image

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] 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的值:

image

其中字典test的具体内容是:

image

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值