把專案從 iOS 7 升到 iOS 8 之後,如果地圖用的是高德地圖 SDK,很可能會遇到一個惱人的狀況:MAMapView 的定位委派確實被呼叫了,但 userLocation.location 卻是 nil。
- (void)mapView:(MAMapView *)mapView
didUpdateUserLocation:(MAUserLocation *)userLocation
updatingLocation:(BOOL)updatingLocation
{
CLLocation *currentLocation = userLocation.location;
if (currentLocation) {
// 在 iOS 8 上永遠不會進到這裡
}
}
委派有觸發、藍點卻不出現,回呼中的 currentLocation 恆為空,定位等於完全失效。
蘋果在 iOS 8 大幅改造了定位服務,新增室內定位、常去地點統計、樓層資訊等能力,同時把授權流程拆成兩階段:
Info.plist 寫入 NSLocationAlwaysUsageDescription,系統就會請求「永久定位」權限。requestWhenInUseAuthorization)與「永遠定位」(requestAlwaysAuthorization)。當時的高德 SDK 尚未針對新流程做適配,沒有代 App 發出授權請求,於是 CLLocationManager 拿不到權限,回傳的位置自然為空。
在專案的 Info.plist 加入對應欄位(兩者用途不同,依需求擇一或都加):
NSLocationWhenInUseDescription——「使用 App 期間」定位時顯示的說明文字NSLocationAlwaysUsageDescription——「永遠」定位時顯示的說明文字文字內容請寫清楚「為什麼需要位置」,這是 App Store 審核的重點之一。
關鍵在於 App 自己宣告一個 CLLocationManager,並在啟動時發出授權請求。
#import <CoreLocation/CoreLocation.h>
@interface AppDelegate () <CLLocationManagerDelegate>
{
UINavigationController *_navController;
CLLocationManager *_locationManager;
}
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[UIApplication sharedApplication].idleTimerDisabled = YES;
_locationManager = [[CLLocationManager alloc] init];
// 對應 Info.plist 的 NSLocationAlwaysUsageDescription
[_locationManager requestAlwaysAuthorization];
// 對應 Info.plist 的 NSLocationWhenInUseDescription
[_locationManager requestWhenInUseAuthorization];
_locationManager.delegate = self;
return YES;
}
@end
完成這兩步之後,高德的定位回呼就能正常運作:
- (void)mapView:(MAMapView *)mapView
didUpdateUserLocation:(MAUserLocation *)userLocation
updatingLocation:(BOOL)updatingLocation
{
if (userLocation.location) {
// 這裡已經拿得到真實座標
}
}
locationManager:didChangeAuthorizationStatus: 給出提示或引導至設定頁。allowsBackgroundLocationUpdates 與 Background Modes。一句話總結:iOS 8 之後,「有寫 plist 說明」不等於「已經請求授權」,兩件事必須都做。