隨著 iOS 10 發表,App 的適配工作隨之而來。以下整理實務上最容易出問題的幾個面向,若有疏漏之處也歡迎指正。
專案中若需要判斷系統版本,請避免使用這種寫法:
#define isiOS10 ([[[[UIDevice currentDevice] systemVersion] substringToIndex:1] intValue] >= 10)
它會永遠回傳 NO,因為 substringToIndex:1 在 iOS 10 上取到的是 "1",被判成 iOS 1。正確做法有以下幾種。
Objective-C 可用版本比較巨集:
#define SYSTEM_VERSION_EQUAL_TO(v) \
([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v) \
([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) \
([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v) \
([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v) \
([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)
或者直接使用 NSProcessInfo:
if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion:
(NSOperatingSystemVersion){.majorVersion = 10, .minorVersion = 0, .patchVersion = 0}]) {
NSLog(@"iOS 10 以上");
}
也可以搭配 NSFoundationVersionNumber 做比較:
if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_9_0) {
// iOS 9 之後的處理
} else {
// 舊版本的處理
}
這些常數定義在 NSObjCRuntime.h 中。Xcode 7.3.1 時期只定義到 iOS 8.4,到了 iOS 10(Xcode 8)Apple 才把缺少的數字補齊:
#define NSFoundationVersionNumber_iOS_9_0 1240.1 #define NSFoundationVersionNumber_iOS_9_1 1241.14 #define NSFoundationVersionNumber_iOS_9_2 1242.12 #define NSFoundationVersionNumber_iOS_9_3 1242.12 #define NSFoundationVersionNumber_iOS_9_4 1280.25 #define NSFoundationVersionNumber_iOS_9_x_Max 1299
Swift 則有兩種選擇:
if NSProcessInfo().isOperatingSystemAtLeastVersion(
NSOperatingSystemVersion(majorVersion: 10, minorVersion: 0, patchVersion: 0)) {
// 程式碼區塊
}
// 或者
if #available(iOS 10.0, *) {
// 新版本
} else {
// 舊版本
}
專案中若存取相機、相簿、聯絡人等隱私資料,用 Xcode 8 編譯後會直接 crash,控制台會印出提示你缺少 usage description 的訊息。
這是因為 iOS 對使用者安全與隱私的強化:申請各項私有權限時都必須附上描述文字。以前 Xcode 用的是系統預設的權限提示框,現在則要求開發者自行說明用途。解法是在 Info.plist 中補上對應的 key:
<!-- 相簿 --> <key>NSPhotoLibraryUsageDescription</key> <string>App 需要您的同意,才能存取相簿</string> <!-- 相機 --> <key>NSCameraUsageDescription</key> <string>App 需要您的同意,才能存取相機</string> <!-- 麥克風 --> <key>NSMicrophoneUsageDescription</key> <string>App 需要您的同意,才能存取麥克風</string> <!-- 定位(使用期間) --> <key>NSLocationWhenInUseUsageDescription</key> <string>App 需要您的同意,才能在使用期間存取位置</string> <!-- 日曆 --> <key>NSCalendarsUsageDescription</key> <string>App 需要您的同意,才能存取日曆</string> <!-- 提醒事項 --> <key>NSRemindersUsageDescription</key> <string>App 需要您的同意,才能存取提醒事項</string> <!-- 運動與健身 --> <key>NSMotionUsageDescription</key> <string>App 需要您的同意,才能存取運動與健身</string> <!-- 藍牙 --> <key>NSBluetoothPeripheralUsageDescription</key> <string>App 需要您的同意,才能存取藍牙</string> <!-- 媒體資料庫 --> <key>NSAppleMusicUsageDescription</key> <string>App 需要您的同意,才能存取媒體資料庫</string>
若仍不生效,可能還需要申請後台權限:
<key>UIBackgroundModes</key>
<array>
<string>location</string>
<!-- 在此補上後台模式要用的其他權限 -->
</array>
也可以在 Xcode 中選取 target,切到 Capabilities 頁籤,找到 Background Modes 開啟後勾選對應項目。

官方文件提到,多數以 Core 開頭的圖形框架與 AVFoundation 都提升了對擴展像素與廣色域色彩空間的支援。UIKit 現在可以在 sRGB 色彩空間下工作,效能更好,也能在更廣的色域中搭配 sRGB 顏色。若專案中是透過低階 API 自行處理圖形,建議改用 sRGB。為此 UIColor 新增了兩個 API:
- (UIColor *)initWithDisplayP3Red:(CGFloat)displayP3Red
green:(CGFloat)green
blue:(CGFloat)blue
alpha:(CGFloat)alpha NS_AVAILABLE_IOS(10_0);
+ (UIColor *)colorWithDisplayP3Red:(CGFloat)displayP3Red
green:(CGFloat)green
blue:(CGFloat)blue
alpha:(CGFloat)alpha NS_AVAILABLE_IOS(10_0);
真彩色顯示會依光感應器自動調節,在不同環境下取得顯示效果與效能的平衡。若需要這個功能,可在 Info.plist 中設定:
<key>UIWhitePointAdaptivityStyle</key> <string>UIWhitePointAdaptivityStyleReading</string>
共有五種取值:
UIWhitePointAdaptivityStyleStandard // 標準模式 UIWhitePointAdaptivityStyleReading // 閱讀模式 UIWhitePointAdaptivityStylePhoto // 圖片模式 UIWhitePointAdaptivityStyleVideo // 影片模式 UIWhitePointAdaptivityStyleGame // 遊戲模式
效果由標準往遊戲依次遞增。也就是說,若你的 App 屬於閱讀類,選 Reading 即可;反之若是圖片處理類卻選了更「好」的模式,反而會拖累效能。
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>sina.cn</key>
<dict>
<key>NSThirdPartyExceptionMinimumTLSVersion</key>
<string>TLSv1.0</string>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
<!-- weibo.cn、weibo.com、sinaimg.cn、sinajs.cn、sina.com.cn 依相同格式設定 -->
</dict>
</dict>
iOS 10 中,若仍使用舊的方式設定狀態列的樣式或控制顯示隱藏,會收到方法已廢棄的警告。請改用下列屬性與方法:
// 由 UIViewController 覆寫 @property(nonatomic, readonly) UIStatusBarStyle preferredStatusBarStyle; // 預設 UIStatusBarStyleDefault @property(nonatomic, readonly) BOOL prefersStatusBarHidden; // 預設 NO - (UIStatusBarAnimation)preferredStatusBarUpdateAnimation; // 預設 UIStatusBarAnimationFade // 需要變更時,主動要求系統更新 [self setNeedsStatusBarAppearanceUpdate];
iOS 10 為 UITextField 新增了 textContentType 屬性,型別為 UITextContentType。它的作用是讓系統得以分析使用者輸入的語意:判斷為電話就建議電話號碼,判斷為地址就建議地址,對於自動填寫與鍵盤智慧提示都有明顯幫助。可選值定義在 UITextInputTraits.h 中,包含姓名、職稱、組織、地址各欄位、電話、Email、URL、信用卡號等選項。
iOS 10 把通知相關 API 全部統一,並在此基礎上大幅擴充自訂能力,也能攔截各個通知狀態的回呼。以前的通知模式是「大家先做好準備,統一散發,沒收到也不關心」;現在則類似網路請求,先送出 request 再取得 response,還封裝了 error,讓你能在各個狀態的方法中做額外處理,並取得 sender 等欄位資訊。相關標頭檔如下:
#import <UserNotifications/UserNotifications.h> #import <UserNotifications/UNError.h> #import <UserNotifications/UNNotification.h> #import <UserNotifications/UNNotificationAction.h> #import <UserNotifications/UNNotificationAttachment.h> #import <UserNotifications/UNNotificationCategory.h> #import <UserNotifications/UNNotificationContent.h> #import <UserNotifications/UNNotificationRequest.h> #import <UserNotifications/UNNotificationResponse.h> #import <UserNotifications/UNNotificationSettings.h> #import <UserNotifications/UNNotificationSound.h> #import <UserNotifications/UNNotificationTrigger.h> #import <UserNotifications/UNUserNotificationCenter.h> #import <UserNotifications/UNNotificationServiceExtension.h>
在 iOS 10 之前,若 UICollectionView 上有大量 cell,使用者快速滑動時卡頓會相当明顯。原因在於舊的 reuse 機制:cell 準備進入螢幕時,整批(整整一列)cell 都已經載入完成並在螢幕外待命,這就是造成卡頓的主因,也就是所謂的掉幀。要讓使用者感覺順暢,App 必須達到 60fps,也就是每 16 毫秒完成一幀刷新。
兩個關鍵差異值得注意。第一,以前 cell 只能從 reuse 佇列取出後重走一遍生命週期,並透過 cellForItemAtIndexPath 重新生成;而在 iOS 10 中,系統會把離開螢幕的 cell 保留一段時間,使用者若滑回來,就不必重走生命週期,只需呼叫 willDisplayCell 即可重新出現。第二,iOS 10 改為「一次一個」載入 cell,而非舊版的「一次一列」,這正是效能提升的主要來源。
為進一步降低 cell 載入耗時,iOS 10 新增了 UICollectionViewDataSourcePrefetching 協議,其中定義兩個方法:
- (void)collectionView:(UICollectionView *)collectionView prefetchItemsAtIndexPaths:(NSArray *)indexPaths NS_AVAILABLE_IOS(10_0); - (void)collectionView:(UICollectionView *)collectionView cancelPrefetchingForItemsAtIndexPaths:(NSArray *)indexPaths NS_AVAILABLE_IOS(10_0);
其中 prefetchItemsAtIndexPaths 是同步之外的異步預先載入,傳入的 indexPaths 為有序陣列,代表 item 接收資料的順序;cancelPrefetchingForItemsAtIndexPaths 則是選用方法,可用於在滑動過程中取消或降低預先載入的優先級。
要特別注意的是,這個協議並不能取代既有的資料來源方法,它只是輔助性的預先載入機制。而且 Pre-Fetching 對 UITableViewCell 同樣適用。
iOS 10 中,UIRefreshControl 可以直接用在 UICollectionView 與 UITableView 上,不再需要透過 UITableViewController。現在它是 UIScrollView 的一個屬性:
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
[refreshControl addTarget:self
action:@selector(loadData)
forControlEvents:UIControlEventValueChanged];
collectionView.refreshControl = refreshControl;