iOS 后台持续定位

环境: xcode8.2.1
1.Target->Capabilities->Background modes,勾选Location updates


iOS 后台持续定位_第1张图片
后台定位

2.请求权限 在info.plist添加
NSLocationWhenInUseUsageDescription、NSLocationAlwaysUsageDescription

权限请求

3.导入系统库

import

4.代理

Paste_Image.png

5.locationManager初始化

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
//若不设置 app会在进入后台20分钟后停止
    self.locationManager.pausesLocationUpdatesAutomatically = NO;
    [self findMe];  
}

6.实现

- (void)findMe
{
    
    if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
        NSLog(@"requestAlwaysAuthorization");
        [self.locationManager requestAlwaysAuthorization];
    }
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9) {
        self.locationManager.allowsBackgroundLocationUpdates = YES;
    }
    
    [self.locationManager startUpdatingLocation];
    NSLog(@"start location");
}

7.获取位置信息

- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations
{
    // 1.获取用户位置的对象
    CLLocation *location = [locations lastObject];
    CLLocationCoordinate2D coordinate = location.coordinate;
        NSLog(@"%@纬度:%f 经度:%f",[NSDate date],coordinate.latitude, coordinate.longitude);

}

8.源码:
https://github.com/Liangjianghao/backgroudLocation.git

你可能感兴趣的:(iOS 后台持续定位)