您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 10 適配踩坑清單:從系統判斷到 ATS 的十大要注意事項

編輯:iOS 開發綜合

iOS 10 的到來意味著一批舊寫法會失效、崩潰或收到警告。以下整理出實際遷移過程中最容易出問題的十個環節,涵蓋系統版本判斷、隱私權限、色彩、通知、列表效能與網路安全。若內容有誤,歡迎指正。

1. 系統版本判斷方法失效

專案裡如果需要判斷系統版本,請不要用這種取第一位字元再轉整數的寫法:

#define isiOS10 ([[[[UIDevice currentDevice] systemVersion] substringToIndex:1] intValue] >= 10)

它會永遠回傳 NO。原因很簡單:「iOS 10.0」被 substringToIndex:1 切完只剩「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 = 9, .minorVersion = 1, .patchVersion = 0}]) {
    NSLog(@"Hello from > iOS 9.1");
}

if ([NSProcessInfo processInfo] isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){9, 3, 0}]) {
    NSLog(@"Hello from > iOS 9.3");
}

另一種方式是比對 Foundation 版本常數:

if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_9_0) {
    // iOS 9 以上的處理
} else {
    // 更舊版本的處理
}

這些常數定義在 NSObjCRuntime.h 中。早期 Xcode 只定義到 iOS 8.4,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 則有兩種寫法:

if NSProcessInfo().isOperatingSystemAtLeastVersion(NSOperatingSystemVersion(majorVersion: 10, minorVersion: 0, patchVersion: 0)) {
    // 程式碼區塊
}
if #available(iOS 10.0, *) {
    // 程式碼區塊
} else {
    // 相容舊版本的程式碼區塊
}

2. 隱私資料存取必須宣告用途說明

只要 App 存取相機、相簿、聯絡人等隱私資料,用 Xcode 8 編譯後一呼叫就會直接 crash, console 會印出類似下面的錯誤:

這是 iOS 對隱私保護加強的結果:申請這類權限時必須附上用途說明。Xcode 8 之前只會跳系統預設的權限提示框,現在少了描述就直接終止程式。

解法是在 Info.plist 中補上對應的 key,value 依實際情境填寫即可。以下列出常用對應關係(Source Code 模式):

<!-- 相簿 -->
<key>NSPhotoLibraryUsageDescription</key>
<string>App 需要您的同意才能存取相簿</string>

<!-- 相機 -->
<key>NSCameraUsageDescription</key>
<string>App 需要您的同意才能存取相機</string>

<!-- 麥克風 -->
<key>NSMicrophoneUsageDescription</key>
<string>App 需要您的同意才能存取麥克風</string>

<!-- 位置 -->
<key>NSLocationUsageDescription</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>

如果 App 需要在背景執行並持續使用上述能力,還要額外申請背景模式:

<key>UIBackgroundModes</key>
<array>
    <!-- 在此填入背景模式對應的 key -->
    <string>location</string>
</array>

也可以在 Xcode 中選取 Target → Capabilities → Background Modes,打開後勾選需要的權限,效果相同。

3. 色彩空間:改用 sRGB

官方文件指出,多數 Core 系列繪圖框架與 AVFoundation 都提升了對擴充像素與廣色域色彩空間的支援。UIKit 現在可以在 sRGB 色彩空間下工作,效能更好,也能在更廣的色域中正確呈現 sRGB 顏色。

若你的專案透過低階 API 自行處理繪圖,建議改用 sRGB。也就是說,原本用 RGB 轉-color 的地方,最好都換成 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);

4. True Tone 原彩顯示

原彩顯示會依環境光感應器自動調整白平衡,讓畫面在不同光線下都能保持自然,同時兼顧效能。若需要啟用,在 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 屬於圖片處理類,卻選了效果最強的模式,反而會白白拖累效能。

5. ATS 網路安全限制的變化

  1. 從 iOS 9 開始,預設禁止非 HTTPS 的網路連線。可以在 Info.plist 加入 NSAppTransportSecurity 字典,把 NSAllowsArbitraryLoads 設為 YES 來關閉 ATS。
  2. 自 2017 年 1 月 1 日起,新提交的 App 不再允許用 NSAllowsArbitraryLoads 一鍵繞過 ATS。預設情況下,App 只能存取加密強度足夠(TLS 1.2 以上)的 HTTPS 內容。
  3. 較可接受的做法是用 NSExceptionDomains 設定白名單,只對特定網域開放例外。例如 App 集成了第三方登入分享 SDK 時就適用。以下以新浪 SDK 為例(Source Code 模式):
<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>weibo.com</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>
  1. iOS 10 的 Info.plist 新增了 NSAllowsArbitraryLoadsInWebContent,允許 WebView 載入任意網頁,同時仍由 ATS 保護 App 本身的連線。
  2. 安全傳輸不再支援 SSLv3,建議盡快停用 SHA1 與 3DES 這類偏舊的演算法。

6. UIStatusBar 相關 API 被標記為過時

在 iOS 10 中,若還在用舊方式設定狀態列樣式或控制隱藏,編譯時會出現 deprecation 警告:

請改用 ViewController 層級的這組屬性與方法:

@property(nonatomic, readonly) UIStatusBarStyle preferredStatusBarStyle;      // 預設 UIStatusBarStyleDefault
@property(nonatomic, readonly) BOOL prefersStatusBarHidden;                   // 預設 NO

- (UIStatusBarStyle)preferredStatusBarStyle;
- (BOOL)prefersStatusBarHidden;

// 狀態列變化時使用的動畫類型,目前只影響 prefersStatusBarHidden 的變化
- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation;                    // 預設 UIStatusBarAnimationFade

7. UITextField 新增 textContentType

iOS 10 為 UITextField 加入了 textContentType 屬性,型別是列舉 UITextContentType。它的作用是告訴系統這個輸入框語意上是什麼,於是鍵盤的自動補全就能給出合理建議:電話欄位推薦電話、地址欄位推薦地址。可選值定義在 <UIKit/UITextInputTraits.h> 中:

UIKIT_EXTERN UITextContentType const UITextContentTypeName;
UIKIT_EXTERN UITextContentType const UITextContentTypeNamePrefix;
UIKIT_EXTERN UITextContentType const UITextContentTypeGivenName;
UIKIT_EXTERN UITextContentType const UITextContentTypeMiddleName;
UIKIT_EXTERN UITextContentType const UITextContentTypeFamilyName;
UIKIT_EXTERN UITextContentType const UITextContentTypeNameSuffix;
UIKIT_EXTERN UITextContentType const UITextContentTypeNickname;
UIKIT_EXTERN UITextContentType const UITextContentTypeJobTitle;
UIKIT_EXTERN UITextContentType const UITextContentTypeOrganizationName;
UIKIT_EXTERN UITextContentType const UITextContentTypeLocation;
UIKIT_EXTERN UITextContentType const UITextContentTypeFullStreetAddress;
UIKIT_EXTERN UITextContentType const UITextContentTypeStreetAddressLine1;
UIKIT_EXTERN UITextContentType const UITextContentTypeStreetAddressLine2;
UIKIT_EXTERN UITextContentType const UITextContentTypeAddressCity;
UIKIT_EXTERN UITextContentType const UITextContentTypeAddressState;
UIKIT_EXTERN UITextContentType const UITextContentTypeAddressCityAndState;
UIKIT_EXTERN UITextContentType const UITextContentTypeSublocality;
UIKIT_EXTERN UITextContentType const UITextContentTypeCountryName;
UIKIT_EXTERN UITextContentType const UITextContentTypePostalCode;
UIKIT_EXTERN UITextContentType const UITextContentTypeTelephoneNumber;
UIKIT_EXTERN UITextContentType const UITextContentTypeEmailAddress;
UIKIT_EXTERN UITextContentType const UITextContentTypeURL;
UIKIT_EXTERN UITextContentType const UITextContentTypeCreditCardNumber;

8. UserNotifications 統一了通知 API

iOS 10 把原本分散的通知相關 API 全部收攏到 UserNotifications 框架。舊模型是「先把請求排好、一次發出去,之後就不管了」;新模型更接近網路請求:發出一個 request、拿到 response,中間還封裝了 error,每個階段都有回呼可以插入自訂邏輯,也能取得sender 等欄位資訊。

使用方式是引入:

#import <UserNotifications/UserNotifications.h>

框架主要包含以下標頭檔:

#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>

9. UICollectionViewCell 的效能優化

在 iOS 10 之前,當列表有大量 cell 且使用者滑動很快時,卡頓非常明顯。原因出在舊有的重用機制:cell 準備進螢幕時,整整一列 cell 都已經完成載入並在螢幕外待命,這個「整列預先載入」就是掉幀的元兇。要讓使用者感覺順滑,App 必須維持 60fps,也就是每 16 毫秒完成一次刷新。

iOS 10 之前的生命週期

  1. 使用者滑動,螢幕外有 cell 準備載入,從 reuse 佇列取出,呼叫 prepareForReuse 重置狀態並載入新資料。
  2. 繼續滑動時呼叫 cellForItemAtIndexPath:,為 cell 賦值模型並回傳給系統。
  3. cell 即將進入螢幕時呼叫 willDisplayCell:,做最後的調整。
  4. willDisplayCell: 執行完,cell 進入螢幕;完全離開後呼叫 didEndDisplayingCell:。

iOS 10 之後的生命週期

  1. 從 reuse 佇列取出 cell 後,還在螢幕外就提前呼叫 prepareForReuse。舊版是等 cell 上邊緣快進螢幕時才呼叫。
  2. cellForItemAtIndexPath: 中建立 cell、填充資料、刷新狀態的時機同樣提前。
  3. 直到真正需要顯示的那一刻才呼叫 willDisplayCell:,原則是「何時要顯示,何時才呼叫」。
  4. cell 完全離開螢幕後呼叫 didEndDisplayingCell:,並進入重用佇列。

關鍵差異有三點:iOS 10 會把滑出螢幕的 cell 保留一段時間,滑回來時不必重跑整個生命週期,只要呼叫 willDisplayCell: 就能重新出現;載入粒度從「一行一行」變成「一個一個」,大幅降低單次工作量;整體流程更接近按需渲染。

新增的 Pre-Fetching 預先載入

為了進一步降低 cell 載入耗時,iOS 10 新增了 UICollectionViewDataSourcePrefetching 協定,定義兩個方法:

- (void)collectionView:(UICollectionView *)collectionView prefetchItemsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths;
- (void)collectionView:(UICollectionView *)collectionView cancelPrefetchingForItemsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths;

prefetchItemsAtIndexPaths: 用於非同步預先載入資料,傳入的 indexPaths 是有序的,代表 item 接收資料的先後順序。cancelPrefetchingForItemsAtIndexPaths: 是可選方法,用來在使用者滑動時取消或降低預先載入的優先級。

要注意:這個協定只是輔助載入資料,並不能取代既有的資料來源方法。另外,Pre-Fetching 對 UITableViewCell 同樣適用。

10. UIRefreshControl 的使用方式改變

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 適配中最常需要動手修改的地方。整體方向其實很清楚:隱私與網路安全越收越緊,效能機制越做越細,把這些環節提前處理好,後續升級會輕鬆很多。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved