從 iOS 9 升到 iOS 10、從 Xcode 7 換到 Xcode 8,很多老工程會突然冒出一堆問題:系統判斷失效、一訪問相冊就崩潰、狀態列樣式報警告。下面把這些高頻坑點整理成十條,每條都附上可用的寫法。
先看一段曾經很常見、但在 iOS 10 上徹底失效的寫法:
#define isiOS10 ([[[[UIDevice currentDevice] systemVersion] substringToIndex:1] intValue]>=10)
問題在於 substringToIndex:1 只截了第一位,「10.0」會被當成「1」,於是這個宏永遠返回 NO。正確的做法是按版本號做數值比較。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)
關鍵是 NSNumericSearch,它會把版本號當作數字序列來比較,而不是逐字元比大小。也可以直接用 NSProcessInfo 提供的 API:
if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){.majorVersion = 9, .minorVersion = 1, .patchVersion = 0}]) {
// 你的邏輯
}
if ([NSProcessInfo.processInfo isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){9,3,0}]) {
// 你的邏輯
}
還有一種判斷依據是 Foundation 版本號:
if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_9_0) {
// 你的邏輯
} else {
// 你的邏輯
}
這些常量定義在 NSObjCRuntime.h 中。Xcode 7.3.1 時代的常量只覆蓋到 NSFoundationVersionNumber_iOS_8_4(1144.17),iOS 10(Xcode 8)才把後續的數字補齊:
#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 裡同樣可以用 NSProcessInfo:
if NSProcessInfo().isOperatingSystemAtLeastVersion(NSOperatingSystemVersion(majorVersion: 10, minorVersion: 0, patchVersion: 0)) {
// 你的邏輯
}
或者更直白的可用性判斷:
if #available(iOS 10.0, *) {
// 你的邏輯
} else {
// 向下兼容
}
用 Xcode 8 打開老工程,凡是訪問相冊、相機、聯絡人等隱私數據的地方,一運行就 crash,控制台會打印類似下面的日誌:

這是 iOS 對用戶隱私保護加強的結果:從 iOS 10 開始,申請各類私有權限都必須在 Info.plist 裡附上用途說明,而 Xcode 8 之前的舊版系統提示框不再適用。解法很簡單——補上對應的 key,value 寫清楚用途即可(以下為 Source Code 模式):
<!-- 相冊 -->
<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>NSLocationAlwaysUsageDescription</key>
<string>App 需要您的同意才能始終訪問位置</string>
<!-- 日歷 -->
<key>NSCalendarsUsageDescription</key>
<string>App 需要您的同意才能訪問日歷</string>
<!-- 提醒事項 -->
<key>NSRemindersUsageDescription</key>
<string>App 需要您的同意才能訪問提醒事項</string>
<!-- 運動與健身 -->
<key>NSMotionUsageDescription</key>
<string>App 需要您的同意才能訪問運動與健身</string>
<!-- 健康更新 -->
<key>NSHealthUpdateUsageDescription</key>
<string>App 需要您的同意才能訪問健康更新</string>
<!-- 健康分享 -->
<key>NSHealthShareUsageDescription</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;也就是說,項目裡凡是手寫 RGB 轉色的地方,都值得換成 sRGB 版本。UIColor 因此新增了兩個接口:
- (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 中配置(Source Code 模式):
<key>UIWhitePointAdaptivityStyle</key>
它有五種取值:
<string>UIWhitePointAdaptivityStyleStandard</string> // 標準模式
<string>UIWhitePointAdaptivityStyleReading</string> // 閱讀模式
<string>UIWhitePointAdaptivityStylePhoto</string> // 圖片模式
<string>UIWhitePointAdaptivityStyleVideo</string> // 視頻模式
<string>UIWhitePointAdaptivityStyleGame</string> // 遊戲模式
效果強度自上而下遞減。閱讀類 App 選 Reading 比較合適;而如果 App 以圖片處理為主,卻選了閱讀模式,過強的適配反而可能拖累性能。
ATS 的規則這幾年一直在收緊,要點如下:
1)iOS 9 起,默認禁止非 HTTPS 請求。可以在 Info.plist 中添加 NSAppTransportSecurity 字典,把 NSAllowsArbitraryLoads 設為 YES 來關閉 ATS。
2)從 2017 年 1 月 1 日起,新提交的 App 不允許再用 NSAllowsArbitraryLoads 一刀切地繞過 ATS,默認要求訪問 TLS 1.2 以上的加密內容。
3)更推薦的做法是用 NSExceptionDomains 針對特定域名開白名單。比如集成了第三方登錄分享 SDK,就可以只對那些域名放行。以下以新浪系列 SDK 為例:
<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>
<key>weibo.cn</key>
<dict>
<key>NSThirdPartyExceptionMinimumTLSVersion</key>
<string>TLSv1.0</string>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
<key>sinaimg.cn</key>
<dict>
<key>NSThirdPartyExceptionMinimumTLSVersion</key>
<string>TLSv1.0</string>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
<key>sinajs.cn</key>
<dict>
<key>NSThirdPartyExceptionMinimumTLSVersion</key>
<string>TLSv1.0</string>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
<key>sina.com.cn</key>
<dict>
<key>NSThirdPartyExceptionMinimumTLSVersion</key>
<string>TLSv1.0</string>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
</dict>
4)iOS 10 的 Info.plist 新增了 NSAllowsArbitraryLoadsInWebContent,允許 Web 內容按需加載,同時由 ATS 保護 App 自身的網絡請求。
5)安全傳輸不再支持 SSLv3,並建議盡快停用 SHA1 和 3DES 這類老舊算法。
在 iOS 10 中,直接改寫狀態列樣式或顯示狀態的老接口會報「方法過期」的警告:

取而代之的是下面這組屬性與方法,由視圖控制器自己聲明偏好:
@property(nonatomic, readonly) UIStatusBarStyle preferredStatusBarStyle NS_AVAILABLE_IOS(7_0) __TVOS_PROHIBITED; // 默認 UIStatusBarStyleDefault
@property(nonatomic, readonly) BOOL prefersStatusBarHidden NS_AVAILABLE_IOS(7_0) __TVOS_PROHIBITED; // 默認 NO
- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation NS_AVAILABLE_IOS(7_0) __TVOS_PROHIBITED; // 默認 UIStatusBarAnimationFade
// 需要更新時主動通知系統
[self setNeedsStatusBarAppearanceUpdate];
iOS 10 給 UITextField 加了 textContentType 屬性,類型是枚舉 UITextContentType。它的作用是告訴系統這個輸入框語義上是什麼,從而在鍵盤上方給出更貼近的聯想建議:是電話就建議號碼,是地址就建議地址。定義可以在 UITextInputTraits.h 中查看,可選值相當豐富:
UIKIT_EXTERN UITextContentType const UITextContentTypeName NS_AVAILABLE_IOS(10_0);
UIKIT_EXTERN UITextContentType const UITextContentTypeNamePrefix NS_AVAILABLE_IOS(10_0);
UIKIT_EXTERN UITextContentType const UITextContentTypeGivenName NS_AVAILABLE_IOS(10_0);
UIKIT_EXTERN UITextContentType const UITextContentTypeMiddleName NS_AVAILABLE_IOS(10_0);
UIKIT_EXTERN UITextContentType const UITextContentTypeFamilyName NS_AVAILABLE_IOS(10_0);
UIKIT_EXTERN UITextContentType const UITextContentTypeNameSuffix NS_AVAILABLE_IOS(10_0);
UIKIT_EXTERN UITextContentType const UITextContentTypeNickname NS_AVAILABLE_IOS(10_0);
UIKIT_EXTERN UITextContentType const UITextContentTypeJobTitle NS_AVAILABLE_IOS(10_0);
UIKIT_EXTERN UITextContentType const UITextContentTypeOrganizationName NS_AVAILABLE_IOS(10_0);
UIKIT_EXTERN UITextContentType const UITextContentTypeLocation NS_AVAILABLE_IOS(10_0);
UIKIT_EXTERN UITextContentType const UITextContentTypeFullStreetAddress NS_AVAILABLE_IOS(10_0);
UIKIT_EXTERN UITextContentType const UITextContentTypeStreetAddressLine1 NS_AVAILABLE_IOS(10_0);
UIKIT_EXTERN UITextContentType const UITextContentTypeStreetAddressLine2 NS_AVAILABLE_IOS(10_0);
UIKIT_EXTERN UITextContentType const UITextContentTypeAddressCity NS_AVAILABLE_IOS(10_0);
UIKIT_EXTERN UITextContentType const UITextContentTypeAddressState NS_AVAILABLE_IOS(10_0);
UIKIT_EXTERN UITextContentType const UITextContentTypeAddressCityAndState NS_AVAILABLE_IOS(10_0);
UIKIT_EXTERN UITextContentType const UITextContentTypeSublocality NS_AVAILABLE_IOS(10_0);
UIKIT_EXTERN UITextContentType const UITextContentTypeCountryName NS_AVAILABLE_IOS(10_0);
UIKIT_EXTERN UITextContentType const UITextContentTypePostalCode NS_AVAILABLE_IOS(10_0);
UIKIT_EXTERN UITextContentType const UITextContentTypeTelephoneNumber NS_AVAILABLE_IOS(10_0);
UIKIT_EXTERN UITextContentType const UITextContentTypeEmailAddress NS_AVAILABLE_IOS(10_0);
UIKIT_EXTERN UITextContentType const UITextContentTypeURL NS_AVAILABLE_IOS(10_0);
UIKIT_EXTERN UITextContentType const UITextContentTypeCreditCardNumber NS_AVAILABLE_IOS(10_0);
iOS 10 把分散的通知相關接口整合進 UserNotifications 框架,同時支持自定義通知內容,並能對各個通知狀態做回調。
以前的通知模型比較「一次性」:應用提前準備好內容,一次性分發出去,之後既不關心投遞結果,也拿不到發送狀態。現在的通知更接近網絡請求的思維——先發一個 request,再拿到 response,中間還封裝了 error,可以在各個階段插入自己的邏輯,也能讀取到通知的附屬信息。
入口頭文件是:
#import <UserNotifications/UserNotifications.h>
框架主要由這些頭文件構成:
#import <UserNotifications/NSString+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 數量很大、用戶滑動又比較快時,卡頓會非常明顯。這就是所謂的「掉幀」。
原因在於舊的加載機制:cell 準備進屏時,整個 cell(往往是整整一行)都已經完成加載並在屏幕外排隊等待。要讓滑動感覺順暢,App 需要維持 60fps,也就是每 16 毫秒必須完成一幀刷新。
1)用戶滑動,屏幕外一個 cell 準備進屏,從 reuse 隊列取出,調用 prepareForReuse,在其中重置狀態、準備新數據;
2)繼續滑動,調用 cellForItemAtIndexPath 給 cell 賦值模型並返回給系統;
3)cell 即將進入屏幕時調用 willDisplayCell,做最後的調整;
4)willDisplayCell 執行完,cell 進屏。當 cell 完全離開屏幕,調用 didEndDisplayingCell。
1)prepareForReuse 的時機提前了——不再等到 cell 上邊緣快進屏,而是 cell 還在屏幕外就調用;
2)cellForItemAtIndexPath 中創建 cell、填充數據、刷新狀態的時機同樣提前;
3)willDisplayCell 的調用原則變成「何時需要顯示,何時才調用」;
4)cell 完全離屏後調用 didEndDisplayingCell,之後進入重用隊列。
兩個關鍵改進值得記住:
第一,系統會把離屏 cell 保留一段時間。用戶滑走後再滑回來,cell 不必重走一遍生命週期,只要調用 willDisplayCell 就能重新出現。
第二,iOS 10 是一個一個加載 cell,而以前是一行一行加載,這是性能提升的主要來源。
為了進一步降低 cell 加載耗時,iOS 10 在數據源與代理協議之外新增了 UICollectionViewDataSourcePrefetching 協議,定義了兩個方法:
- (void)collectionView:(UICollectionView *)collectionView prefetchItemsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths NS_AVAILABLE_IOS(10_0);
- (void)collectionView:(UICollectionView *)collectionView cancelPrefetchingForItemsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths NS_AVAILABLE_IOS(10_0);
prefetchItemsAtIndexPaths: 用於異步預加載數據,傳入的 indexPaths 是有序數組,順序即 item 接收數據的先後;cancelPrefetchingForItemsAtIndexPaths: 是可選方法,用來在快速滑動時取消或降低提前加載的優先級。
注意:這個協議不能替代原有的數據讀取方法,它只是輔助手段。而且它對 UITableViewCell 同樣適用。
iOS 10 中,UIRefreshControl 可以直接用在 UICollectionView 和 UITableView 上,不再依賴 UITableViewController——它已經成為 UIScrollView 的一個屬性。
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
[refreshControl addTarget:self action:@selector(loadData) forControlEvents:UIControlEventValueChanged];
collectionView.refreshControl = refreshControl;
以上就是 iOS 10 適配中最容易踩到的十個點。遇到問題歡迎一起討論,內容也會持續補充。