萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> iOS 開發

iOS 8 定位權限適配全攻略:Info.plist 配置與請求授權代碼

核心變化

iOS 8 引入分級定位權限:

  • 前台定位:App 可見時獲取位置 → NSLocationWhenInUseUsageDescription
  • 後台定位:App 掛起/關閉時仍獲取位置 → NSLocationAlwaysUsageDescription

缺少對應 Info.plist 鍵值 → 定位直接靜默失敗,無任何彈窗、無任何錯誤回調,這是最大坑點。

Info.plist 必加鍵值

<key>NSLocationWhenInUseUsageDescription</key>
<string>我們需要您的位置信息以提供附近服務</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>我們需要後台位置以記錄軌跡/推送本地通知</string>

字符串將顯示在系統權限彈窗中,請清晰說明用途,否則審核易被拒。

代碼實現:版本兼容與雙權限請求

- (void)startLocationUpdates {
    if (![CLLocationManager locationServicesEnabled]) return;

    if (!_locationManager) _locationManager = [[CLLocationManager alloc] init];
    _locationManager.delegate = self;
    _locationManager.distanceFilter = 1.0;
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;

    // iOS 8+ 才有這兩個選擇器
    if ([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
        // 根據業務需求選擇一個或兩個都請求
        [_locationManager requestWhenInUseAuthorization];  // 前台
        // [_locationManager requestAlwaysAuthorization];   // 後台(需對應 Always 鍵值)
    }

    [_locationManager startUpdatingLocation];
}

// Delegate
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusAuthorizedAlways) {
        [manager startUpdatingLocation]; // 用戶授權後自動開始(若之前已調用 startUpdatingLocation 會在授權瞬間觸發)
    }
}

關鍵注意點

  1. 請求時機:建議在功能頁面進入時(如地圖頁)請求,而非啟動時強請,提高授權率
  2. 雙重請求:先請 WhenInUse,用戶拒絕後可稍後引導開啟 Always(需跳轉設定頁)
  3. 後台定位持久化:需在 Capabilities → Background Modes 勾選 Location updates
  4. iOS 11+ 新增:NSLocationAlwaysAndWhenInUseUsageDescription 兼容舊鍵值,建議三個全加
  5. 模擬器測試:Debug → Location → 選擇預設/自定義位置

隱私設計哲學轉變

蘋果從「是/否」二元授權進化為「前台/後台/精確/模糊」多維授權,體現最小權限原則。開發者應:

  • 只請求業務必需的最高權限
  • 在授權前向用戶解釋價值(Pre-permission 請求)
  • 優雅處理拒絕狀態:引導進設定頁、降級功能、不阻塞主流程
copyright © 萬盛學電腦網 all rights reserved