本文將給大家介紹如何使用CLLocationManager進(jìn)行后臺(tái)定位板丽。
準(zhǔn)備工作(重要):
在Info.plist文件中配置:
Required background modes-App registers for location updates
NSLocationAlwaysUsageDescription-Location is required to find out where you are(或其他內(nèi)容)
準(zhǔn)備工作完成后,在工程里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系統(tǒng)版本判斷听诸,在iOS9的系統(tǒng)下,如果不使用新方法locationManager.allowsBackgroundLocationUpdates=YES;會(huì)導(dǎo)致定位切換到后臺(tái)后潮瓶,系統(tǒng)不會(huì)開(kāi)啟后臺(tái)運(yùn)行陶冷。
最后實(shí)現(xiàn)代理:
#pragma mark --CLLocationManagerDelegate
-(void)locationManager:(CLLocationManager*)manager didUpdateLocations:(NSArray *)locations {
//TODO:后臺(tái)定位、結(jié)合MKMapView做地圖軌跡......
}
順便給大家說(shuō)明下CLLocationManager的requestWhenInUseAuthorization與requestAlwaysAuthorization的區(qū)別毯辅。
[locationManager requestWhenInUseAuthorization]只在前臺(tái)運(yùn)行模式時(shí)起作用埃叭,如App切換至后臺(tái)運(yùn)行模式,代理方法didUpdateLocations不會(huì)繼續(xù)執(zhí)行悉罕。使用requestWhenInUseAuthorization需要在info.plist里配置:
NSLocationWhenInUseUsageDescription-Location is required to find out where you are(或其他內(nèi)容)
[locationManager requestAlwaysAuthorization]則都可在前臺(tái)赤屋、后臺(tái)模式中運(yùn)行,需要在info.plist里配置:
NSLocationAlwaysUsageDescription-Location is required to find out where you are(或其他內(nèi)容)
不管使用NSLocationWhenInUseUsageDescription還是NSLocationAlwaysUsageDescription壁袄,都需要在info.plist里配置:
Required background modes-App registers for location updates