iOS定位获取城市名(ios自学笔记)

笔者是放在appdelegate里面请求的,需求是定位到当前城市

1、添加corelocation库,这个定位都要用到的,系统自带的


2、 #import <CoreLocation/CoreLocation.h>


3、添加CLLocationManagerDelegate定位代理


4、实例化定位管理器

    _locationManager = [[CLLocationManager alloc] init];

设置代理

    _locationManager.delegate = self;

定位精度

    [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];

请求用户权限:分为:?只在前台开启定位?在后台也可定位,

    //注意:建议只请求??中的一个,如果两个权限都需要,只请求?即可,

    //??这样的顺序,将导致bug:第一次启动程序后,系统将只请求?的权限,?的权限系统不会请求,只会在下一次启动应用时请求?

    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8) {

        //[_locationManager requestWhenInUseAuthorization];//?只在前台开启定位

        [_locationManager requestAlwaysAuthorization];//?在后台也可定位

    }

iOS9新特性:将允许出现这种场景:同一app中多个location manager:一些只能在前台定位,另一些可在后台定位(并可随时禁止其后台定位)。

    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9) {

        _locationManager.allowsBackgroundLocationUpdates = YES;

    } 

更新用户位置 

    [_locationManager startUpdatingLocation];


5、InfoPlist 加字段

<key>UIBackgroundModes</key>

<string>location</string>

<key>NSLocationAlwaysUsageDescription</key>

<string>东XXXXXXXXX</string>


6、定位代理经纬度回调

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

    

    CLLocation *newLocation = locations[0];

    CLLocationCoordinate2D oldCoordinate = newLocation.coordinate;

    NSLog(@"旧的经度:%f,旧的纬度:%f",oldCoordinate.longitude,oldCoordinate.latitude);

    

    [manager stopUpdatingLocation];

    

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

    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {

        

        for (CLPlacemark *place in placemarks) {

            NSLog(@"name,%@",place.name);                       // 位置名

            NSLog(@"thoroughfare,%@",place.thoroughfare);       // 街道

            NSLog(@"subThoroughfare,%@",place.subThoroughfare); // 子街道

            NSLog(@"locality,%@",place.locality);               //

            NSLog(@"subLocality,%@",place.subLocality);         //

            NSLog(@"country,%@",place.country);                 // 国家

            

            id selectedLocationName = [[NSUserDefaults standardUserDefaults] objectForKey:UDK_SELECTED_LOCATION];

            if(selectedLocationName == nil)

            {

                [[NSUserDefaults standardUserDefaults] setObject:place.locality forKey:UDK_SELECTED_LOCATION];

                [[NSUserDefaults standardUserDefaults] synchronize];

            }

        }

    }];

}


调试后:


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wangyang6275

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值