iOS 8 引入分級定位權限:
NSLocationWhenInUseUsageDescriptionNSLocationAlwaysUsageDescription缺少對應 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 會在授權瞬間觸發)
}
}
WhenInUse,用戶拒絕後可稍後引導開啟 Always(需跳轉設定頁)NSLocationAlwaysAndWhenInUseUsageDescription 兼容舊鍵值,建議三個全加蘋果從「是/否」二元授權進化為「前台/後台/精確/模糊」多維授權,體現最小權限原則。開發者應: