從 iOS 7 升級到 iOS 8 後,不少原本正常的應用會出現各種問題。本文整理了三個常見的坑與對應解法:定位、模擬器鍵盤、以及推送。
在「設定 > 隱私 > 定位服務」中勾選了「使用應用程式期間」,但打開 app 再回到設定,卻發現勾選又被取消了。原因是 iOS 8 需要開發者在程式碼中主動請求授權。
解法如下:
startUpdatingLocation 前呼叫 requestWhenInUseAuthorization;requestAlwaysAuthorization;NSLocationWhenInUseUsageDescription 或 NSLocationAlwaysUsageDescription 欄位,值填寫向使用者說明用途的文字(如「需要定位」),這段文字會在詢問授權時顯示。
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
[_locationManager requestWhenInUseAuthorization];
}
[_locationManager startUpdatingLocation];
若 iOS 模擬器的實體鍵盤無法輸入,可透過選單修正:
iOS Simulator > Hardware > Keyboard,取消勾選「Connect Hardware Keyboard」。
iOS 8 修改了通知註冊的 API,需要區分版本處理:
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
[app registerForRemoteNotifications];
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:
UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound
categories:nil];
[app registerUserNotificationSettings:settings];
} else {
[app registerForRemoteNotificationTypes:
UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound];
}
iOS 8 在定位授權與通知註冊上引入了更細緻的 API 變革。掌握這些差異並做好版本判斷,就能讓應用在舊版與新版系統上都能正常運作。