定位

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

2、 #import <CoreLocation/CoreLocation.h>

3、添加CLLocationManagerDelegate定位代理

4、实例化定位管理器

    _locationManager = [[CLLocationManageralloc] init];

设置代理

    _locationManager.delegate =self;

定位精度

    [_locationManagersetDesiredAccuracy:kCLLocationAccuracyBest];

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

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

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

    if ([[[UIDevicecurrentDevice] systemVersion]floatValue] >= 8) {

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

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

    }

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

    if ([[[UIDevicecurrentDevice] systemVersion]floatValue] >= 9) {

        _locationManager.allowsBackgroundLocationUpdates =YES;

    } 

更新用户位置 

    [_locationManagerstartUpdatingLocation];

5、InfoPlist 加字段

<key>UIBackgroundModes</key>

<string>location</string>

<key>NSLocationAlwaysUsageDescription</key>

<string></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 = [[CLGeocoderalloc]init];

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

        

        for (CLPlacemark *placein 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 = [[NSUserDefaultsstandardUserDefaults] objectForKey:UDK_SELECTED_LOCATION];

            if(selectedLocationName ==nil)

            {

                [[NSUserDefaultsstandardUserDefaults] setObject:place.localityforKey:UDK_SELECTED_LOCATION];

                [[NSUserDefaultsstandardUserDefaults] synchronize];

            }

        }

    }];

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值