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

iOS 10 適配重點整理:從系統判斷到列表效能優化

編輯:iOS 開發綜合

隨著 iOS 10 發表,App 的適配工作隨之而來。以下整理實務上最容易出問題的幾個面向,若有疏漏之處也歡迎指正。

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

專案中若需要判斷系統版本,請避免使用這種寫法:

#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 {
    // 舊版本
}

2. 隱私資料存取需要描述文字

專案中若存取相機、相簿、聯絡人等隱私資料,用 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 開啟後勾選對應項目。

3. 色彩空間的調整

官方文件提到,多數以 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);

4. 真彩色顯示

真彩色顯示會依光感應器自動調節,在不同環境下取得顯示效果與效能的平衡。若需要這個功能,可在 Info.plist 中設定:

<key>UIWhitePointAdaptivityStyle</key>
<string>UIWhitePointAdaptivityStyleReading</string>

共有五種取值:

UIWhitePointAdaptivityStyleStandard   // 標準模式
UIWhitePointAdaptivityStyleReading    // 閱讀模式
UIWhitePointAdaptivityStylePhoto      // 圖片模式
UIWhitePointAdaptivityStyleVideo      // 影片模式
UIWhitePointAdaptivityStyleGame       // 遊戲模式

效果由標準往遊戲依次遞增。也就是說,若你的 App 屬於閱讀類,選 Reading 即可;反之若是圖片處理類卻選了更「好」的模式,反而會拖累效能。

5. ATS(App Transport Security)

  1. 從 iOS 9 起,預設禁止非 HTTPS 的網路連線。可在 Info.plist 加入 NSAppTransportSecurity 字典,把 NSAllowsArbitraryLoads 設為 YES 以關閉 ATS。
  2. 自 2017 年 1 月 1 日起,所有新提交的 App 不再允許用 NSAllowsArbitraryLoads 繞過 ATS 限制。預設情況下 App 只能存取加密強度足夠(TLS 1.2 以上)的 HTTPS 內容。
  3. 可以改用 NSExceptionDomains 針對特定網域開放 HTTP,以通過審核。例如整合第三方登入分享 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>
        <!-- weibo.cn、weibo.com、sinaimg.cn、sinajs.cn、sina.com.cn 依相同格式設定 -->
    </dict>
</dict>
  1. iOS 10 在 Info.plist 新增了 NSAllowsArbitraryLoadsInWebContent,允許任意網頁內容載入,同時仍由 ATS 保護你的 App。
  2. 安全傳輸不再支援 SSLv3,建議尽速停用 SHA1 與 3DES 等過時演算法。

6. UIStatusBar 的 API 變更

iOS 10 中,若仍使用舊的方式設定狀態列的樣式或控制顯示隱藏,會收到方法已廢棄的警告。請改用下列屬性與方法:

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

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation;                 // 預設 UIStatusBarAnimationFade

// 需要變更時,主動要求系統更新
[self setNeedsStatusBarAppearanceUpdate];

7. UITextField 的 textContentType

iOS 10 為 UITextField 新增了 textContentType 屬性,型別為 UITextContentType。它的作用是讓系統得以分析使用者輸入的語意:判斷為電話就建議電話號碼,判斷為地址就建議地址,對於自動填寫與鍵盤智慧提示都有明顯幫助。可選值定義在 UITextInputTraits.h 中,包含姓名、職稱、組織、地址各欄位、電話、Email、URL、信用卡號等選項。

8. UserNotifications 框架

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>

9. UICollectionViewCell 的效能優化

在 iOS 10 之前,若 UICollectionView 上有大量 cell,使用者快速滑動時卡頓會相当明顯。原因在於舊的 reuse 機制:cell 準備進入螢幕時,整批(整整一列)cell 都已經載入完成並在螢幕外待命,這就是造成卡頓的主因,也就是所謂的掉幀。要讓使用者感覺順暢,App 必須達到 60fps,也就是每 16 毫秒完成一幀刷新。

iOS 10 之前的生命週期
  1. 使用者滑動螢幕,螢幕外有一個 cell 準備載入:從 reuse 佇列取出,呼叫 prepareForReuse 重置狀態並載入新資料。
  2. 繼續滑動,呼叫 cellForItemAtIndexPath 為 cell 賦值並回傳給系統。
  3. cell 即將進入螢幕時呼叫 willDisplayCell,此時仍可對 cell 做最後調整。
  4. cell 完全離開螢幕後呼叫 didEndDisplayingCell。
iOS 10 之後的生命週期
  1. cell 準備載入時先從 reuse 佇列取出並呼叫 prepareForReuse。差別在於:以前是 cell 上緣即將進入螢幕時才呼叫,現在提前到 cell 還在螢幕外就呼叫。
  2. cellForItemAtIndexPath 中建立 cell、填充資料、刷新狀態等操作,同樣被提前。
  3. 直到 cell 真的需要顯示時才呼叫 willDisplayCell。原則是:何時需要顯示,何時才呼叫。
  4. cell 完全離開螢幕後呼叫 didEndDisplayingCell,之後進入重用佇列。

兩個關鍵差異值得注意。第一,以前 cell 只能從 reuse 佇列取出後重走一遍生命週期,並透過 cellForItemAtIndexPath 重新生成;而在 iOS 10 中,系統會把離開螢幕的 cell 保留一段時間,使用者若滑回來,就不必重走生命週期,只需呼叫 willDisplayCell 即可重新出現。第二,iOS 10 改為「一次一個」載入 cell,而非舊版的「一次一列」,這正是效能提升的主要來源。

Pre-Fetching 預先載入

為進一步降低 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 同樣適用。

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