iOS CoreLocation框架

官方参考文档:https://developer.apple.com/documentation/corelocation/cllocationmanager

  • 导入CoreLocation框架和对应的主头文件

#import <CoreLocation/CoreLocation.h>
  • 创建CLLcationManager对象,并设置代理

_locationM = [[CLLocationManager alloc] init];
_locationM.delegate = self;
if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) 
 {
    //iOS8.0+前台定位授权,并配置Info.plist文件:NSLocationWhenInUseUsageDescription
    [_locationM requestWhenInUseAuthorization];

    //iOS8.0+后台定位授权,并配置Info.plist文件:NSLocationAlwaysUsageDescription
   //[_locationM requestAlwaysAuthorization];
 } 
  • 调用CLLcationManager对象的startUpdatingLocation方法进行更新用户位置

[_locationM startUpdatingLocation];
  • 调用CLLcationManager对象的startUpdatingHeading方法进行更新设备朝向
[_locationM startUpdatingHeading];
  • 调用CLLcationManager对象的startMonitoringForRegion:方法进行监听指定区域
// 创建区域中心
CLLocationCoordinate2D center = CLLocationCoordinate2DMake(29.12345, 131.23456);
// 创建区域(指定区域中心,和区域半径)
 CLCircularRegion *region = [[CLCircularRegion alloc] initWithCenter:center radius:1000 identifier:@"广州"];
// 开始监听指定区域
[self.locationM startMonitoringForRegion:region];
  • 实现代理方法,接收位置更新参数

-(void)locationManager:(nonnull CLLocationManager *)manager didUpdateLocations:(nonnull NSArray<CLLocation *> *)locations
  • 实现代理方法,接收方向更新参数:
-(void)locationManager:(nonnull CLLocationManager *)manager didUpdateHeading:(nonnull CLHeading *)newHeading
  • 实现代理方法,获取区域进入或者离开状态:
// 进去监听区域后调用(调用一次)
-(void)locationManager:(nonnull CLLocationManager *)manager didEnterRegion:(nonnull CLRegion *)region
{
      NSLog(@"进入区域---%@", region.identifier);
      [manager stopMonitoringForRegion:region];
}
// 离开监听区域后调用(调用一次)
-(void)locationManager:(nonnull CLLocationManager *)manager didExitRegion:(nonnull CLRegion *)region
{
      NSLog(@"离开区域---%@", region.identifier);
}


相关配置:

  • iOS8.0后台定位配置:

   

  • iOS8.0+:

  前台定位配置Info.plist文件:

  

  后台定位:

if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) 
 {
    //iOS8.0+后台定位授权,并配置Info.plist文件:NSLocationAlwaysUsageDescription
   [_locationM requestAlwaysAuthorization];
 } 

  配置Info.plist文件: 

  

  • iOS9.0后台定位补充:

可使用iOS8.0+的后台定位方法,也可按照以下方式添加。

勾选后台运行模式Locations Updates,并且调用以下方法,设置允许后台定位:

if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
        _locationM.allowsBackgroundLocationUpdates = YES;
}

猜你喜欢

转载自www.cnblogs.com/Blueleaf-tech/p/9807913.html
今日推荐