CoreLocation获取位置信息简单使用

前言:

项目开发中经常会有获取用户位置的需求,如天气、生活圈、附近的人等

实现:

1、创建一个NSObject类导入 #import

2.在info.plist中加入权限

NSLocationAlwaysUsageDescription (始终,在iOS8-10中使用,iOS11已  Deprecated,官网解析:A message that tells the user why the app is requesting access to the user's location at all times.)

NSLocationWhenInUseUsageDescription(使用应用期间,官网解析:A message that tells the user why the app is requesting access to the user’s location information while the app is running in the foreground.)

NSLocationAlwaysAndWhenInUseUsageDescription(iOS11新增始终获取位置信息 官网解析:A message that tells the user why the app is requesting access to the user’s location information at all times.)

3.在头文件定义location管理类和协议

@interface JCLocation ()

@property (nonatomic, strong) CLLocationManager *locManager;

@property (nonatomic, strong) CLGeocoder *coder; // 反地理编码位置

@end

4.初始化

self.locManager = [[CLLocationManager alloc]init];

self.coder      = [[CLGeocoder alloc]init];

if (@available(iOS 8.0, *)) {   //ios 8需要申请权限

      [self.locManager requestAlwaysAuthorization];        

      [self.locManager requestWhenInUseAuthorization];

}

if (@available(iOS 9.0, *)) {    //iOS9后允许后台刷新

        if ([self.locManager respondsToSelector:@selector(allowsBackgroundLocationUpdates)]) {

          self.locManager.allowsBackgroundLocationUpdates = YES;

}

}

self.locManager.delegate = self;

self.locManager.desiredAccuracy = kCLLocationAccuracyBest;

self.locManager.pausesLocationUpdatesAutomatically = NO; //是否允许自动暂停更新位置默认yes

[self.locManager startUpdatingLocation]; //开始更新位置

5.位置更新后delegate回调

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

{

    if (locations.count > 0) {

        CLLocation *loc = [locations lastObject];

        NSLog(@"lat = %f, long = %f",loc.coordinate.latitude,loc.coordinate.longitude); //至此如果成功就可以打印经纬度信息了

     //以下为反地理编码位置方法,有时候会出现偏差过大,代码中包含WGS84矫正        

        [_coder reverseGeocodeLocation:location    completionHandler:^(NSArray * _Nullable placemarks, NSError * _Nullable error) {

        CLPlacemark *pmark = [placemarks firstObject];

        //CLPlacemark类中包含了国家、地区,城市,街道等详细信息

}];

   }

}

6.定位失败delegate回调

-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error

{  

        switch ([error code]) {

            case kCLErrorNetwork:

                    DLog(@"no network...");

                break;

            case kCLErrorDenied:

                    DLog(@"Access to location or ranging has been denied by the user");

                break;

            default:

                break;

       }

7.停止定位

[self.locManager stopUpdatingLocation];

8.注意

[self.locManager startUpdatingLocation] 不要写成了 [self.locManager startUpdatingHeading];

startUpdatingHeading是更新指南针方向的

本文参考Demo

你可能感兴趣的:(CoreLocation获取位置信息简单使用)