需求:要求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;
}