iOS 后台定位CoreLocation CLLocationManager

需求:要求APP定时向服务器上传自己的位置

1.配置

1.1 将Capablities中的BackgroundMode勾选未ON 并且勾选其中的Location updates选项

1.2 权限设置

Privacy - Location When In Use Usage Description

Privacy - Location Always Usage Description

2. 初始化

导入   #import <CoreLocation/CoreLocation.h>

 _lcManager = [[CLLocationManager alloc] init];
    
 _lcManager.delegate = self;
 _lcManager.desiredAccuracy = kCLLocationAccuracyBest;
 _lcManager.pausesLocationUpdatesAutomatically = NO;

这里后台保持持续定位有两种方式

第一种 

    if ([_lcManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)]) {
        [_lcManager setAllowsBackgroundLocationUpdates:YES];
    }

直接设置这个就可以实现后台定位  但是有个缺点   app进入后台后会有一个蓝色状态条


第二种

判断权限

    if ([_lcManager respondsToSelector:@selector(requestAlwaysAuthorization)])
    {
        [_lcManager requestAlwaysAuthorization];
        [_lcManager requestWhenInUseAuthorization];
    }

- (void)requestAlwaysAuthorization     // 总是给予授权
- (void)requestWhenInUseAuthorization; // 在前台才定位

这个在iOS11之后要求添加Privacy - Location Always and When In Use Usage Description权限

否则进入后台后就不定位了  

3. 代理方法

默认每秒定位一次  

也就是每秒调用一次

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
 定位成功
 
 @param manager <#manager description#>
 @param locations <#locations description#>
 */

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    
    CLLocation *location = [locations lastObject];
    double lat = location.coordinate.latitude;
    double lng = location.coordinate.longitude;
    
    
  

    NSLog(@"------lat:%f, ------lng:%f", lat, lng);
    
    if (!self.deferringUpdates) {
        
        [_lcManager allowDeferredLocationUpdatesUntilTraveled:500 timeout:10];
        
        self.deferringUpdates = YES;
    } 
}


/**
 定位失败
 
 @param manager <#manager description#>
 @param error <#error description#>
 */
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    self.deferringUpdates = NO;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值