本文將給大家介紹如何使用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