您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 8 高德地圖 SDK:MAMapView 定位回呼拿到空值的解法

編輯:iOS 開發綜合

把專案從 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 改了定位授權模型

蘋果在 iOS 8 大幅改造了定位服務,新增室內定位、常去地點統計、樓層資訊等能力,同時把授權流程拆成兩階段:

  • 以往只要在 Info.plist 寫入 NSLocationAlwaysUsageDescription,系統就會請求「永久定位」權限。
  • iOS 8 之後必須在程式碼中主動呼叫授權 API,且要區分「僅使用時定位」(requestWhenInUseAuthorization)與「永遠定位」(requestAlwaysAuthorization)。

當時的高德 SDK 尚未針對新流程做適配,沒有代 App 發出授權請求,於是 CLLocationManager 拿不到權限,回傳的位置自然為空。

解法一:補上 Info.plist 的用途說明

在專案的 Info.plist 加入對應欄位(兩者用途不同,依需求擇一或都加):

  • NSLocationWhenInUseDescription——「使用 App 期間」定位時顯示的說明文字
  • NSLocationAlwaysUsageDescription——「永遠」定位時顯示的說明文字

文字內容請寫清楚「為什麼需要位置」,這是 App Store 審核的重點之一。

解法二:在 AppDelegate 主動請求授權

關鍵在於 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: 給出提示或引導至設定頁。
  • iOS 8 以上另需注意:後續 iOS 版本對「僅使用時」授權與背景定位有更嚴格規範,若需要背景取得位置,還要額外設定 allowsBackgroundLocationUpdates 與 Background Modes。
  • SDK 版本:這個問題在高德 SDK 後續版本中已由官方修正,但理解授權機制的變化本身仍然重要——同類症狀在任何舊版定位相關 SDK 上都可能出現。

一句話總結:iOS 8 之後,「有寫 plist 說明」不等於「已經請求授權」,兩件事必須都做。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved