iOS地理定位 app正常運行時可以,按下home鍵后app在后台也可以,雙擊home鍵后台殺死app也可以,甚至重啟機器后也可以。(iOS 10 測試代碼)
1)設置一些請求參數
就像正常的CLLocationManager一樣申請權限以及后台更新請求
后台更新:
plist請求地理位置(需要跑始終使用)
2)與往常一樣的初始化定位管理器等步驟
CLLocationManager *locationMgr = [[CLLocationManager alloc]init];
[locationMgr setAllowsBackgroundLocationUpdates:YES];
// 判斷手機是否啟用了定位服務
if (![CLLocationManager locationServicesEnabled]) {
NSLog(@"定位服務當前可能尚未打開,請設置打開!");
return;
}
else {
NSLog(@"定位服務已開啟");
}
// 如果沒有授權則請求用戶授權
if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined){
[locationMgr requestAlwaysAuthorization];
NSLog(@"請求用戶授權");
}else
{
NSLog(@"可以使用");
locationMgr.delegate = self;
locationMgr.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
locationMgr.distanceFilter = 0.1;
locationMgr.allowsBackgroundLocationUpdates = YES;
[locationMgr startUpdatingLocation];
[locationMgr startMonitoringSignificantLocationChanges];
}
// 如果地理位置發生了變化則走樓下回調函數
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{}
3)設置后台與銷毀狀態的函數
// 終了時調用
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hehe) name:@"OK" object:UIApplicationWillTerminateNotification];
// 后台時調用
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hehe) name:@"OK" object:UIApplicationDidEnterBackgroundNotification];
-(void)hehe{
[locationMgr startMonitoringSignificantLocationChanges];
[locationMgr startUpdatingLocation];
}
------------->萬事大吉
注意:
1. APP被殺死,再開機時,回調函數反應慢
2.這里有startMonitoringSignificantLocationChanges和startUpdatingLocation兩個方法,一個是顯著位置變化一個是正常,前者被殺死也可喚起走入回調函數,后者必須在APP沒死時才可以被喚起走入回調函數。
附:
startMonitoringSignificantLocationChanges:
https://developer.apple.com/reference/corelocation/cllocationmanager/1423531-startmonitoringsignificantlocati
(就是說就算被殺死也能通過顯著位置變化喚起的意思)
startUpdatingLocation:
https://developer.apple.com/reference/corelocation/cllocationmanager/1423750-startupdatinglocation
(就是說APP被殺死就不會通過位置變化而被喚起的意思)
-=> 可以通過這樣開發一些需要APP自己啟動的APP嘍!(笑)