当前位置: 代码迷 >> 综合 >> iOS 后台定位CoreLocation CLLocationManager
  详细解决方案

iOS 后台定位CoreLocation CLLocationManager

热度:106   发布时间:2023-10-19 05:48:00.0

需求:要求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进入后台后会有一个蓝色状态条

iOS 后台定位CoreLocation CLLocationManager

第二种

判断权限

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

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

iOS 后台定位CoreLocation CLLocationManager

这个在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;
}