標籤:許可權 技術分享 需要 ref dev 運行時 ice nav distance
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嘍!(笑)
iOS後台定位