iOS Developer

iOS使用CLLocationManager进行后台定位

2016-10-04  本文已影响1588人  海文_L

本文将给大家介绍如何使用CLLocationManager进行后台定位。

准备工作重要):

在Info.plist文件中配置:

Required background modes-App registers for location updates

NSLocationAlwaysUsageDescription-Location is required to find out where you are(或其他内容)

准备工作完成后,在工程里CoreLocation framework,在VC里引入头文件#import<CoreLocation/CoreLocation.h>,添加CLLocationManagerDelegate,声明公共变量CLLocationManager*locationManager,在viewDidLoad里添加如下代码:

locationManager =  [[CLLocationManager alloc] init];

locationManager.delegate = self;

[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];

if([[[UIDevice currentDevice] systemVersion]floatValue] >=8) {

[locationManager requestAlwaysAuthorization];

}

if([[[UIDevice currentDevice] systemVersion]floatValue] >=9) {

locationManager.allowsBackgroundLocationUpdates=YES;

}

[locationManager startUpdatingLocation];

这里我们添加了iOS8跟iOS9系统版本判断,在iOS9的系统下,如果不使用新方法locationManager.allowsBackgroundLocationUpdates=YES;会导致定位切换到后台后,系统不会开启后台运行。

最后实现代理:

#pragma mark --CLLocationManagerDelegate

-(void)locationManager:(CLLocationManager*)manager didUpdateLocations:(NSArray *)locations {

//TODO:后台定位、结合MKMapView做地图轨迹......

}

顺便给大家说明下CLLocationManager的requestWhenInUseAuthorization与requestAlwaysAuthorization的区别。

[locationManager requestWhenInUseAuthorization]只在前台运行模式时起作用,如App切换至后台运行模式,代理方法didUpdateLocations不会继续执行。使用requestWhenInUseAuthorization需要在info.plist里配置:

NSLocationWhenInUseUsageDescription-Location is required to find out where you are(或其他内容)

[locationManager requestAlwaysAuthorization]则都可在前台、后台模式中运行,需要在info.plist里配置:

NSLocationAlwaysUsageDescription-Location is required to find out where you are(或其他内容)

不管使用NSLocationWhenInUseUsageDescription还是NSLocationAlwaysUsageDescription,都需要在info.plist里配置:

Required background modes-App registers for location updates

上一篇下一篇

猜你喜欢

热点阅读