iOS 11 & iPhoneX 適配

wentianen發表於2017-12-02

一、safeArea

  1. automaticallyAdjustsScrollViewInsets to contentInsetAdjustmentBehavior 在iOS 11中,蘋果廢棄了 UIViewControllerautomaticallyAdjustsScrollViewInsets屬性,改用UIScrollViewcontentInsetAdjustmentBehavior 屬性來替換它。
// OC
@property(nonatomic,assign) BOOL automaticallyAdjustsScrollViewInsets API_DEPRECATED_WITH_REPLACEMENT("Use UIScrollView's contentInsetAdjustmentBehavior instead", ios(7.0,11.0),tvos(7.0,11.0)); // Defaults to YES

//swift
@available(iOS, introduced: 7.0, deprecated: 11.0)
open var automaticallyAdjustsScrollViewInsets: Bool // Defaults to YES
複製程式碼

如果你的工程中沒有新增 iPhone X 對應的啟動圖,你會發現頂部和底部的一部分都是黑色的,那部分就是安全域。 想要對 iPhone X 做螢幕適配,第一步先要新增啟動圖。

image.png

二、UITableView 自動計算高度

在iOS 11中,UITableViewestimatedRowHeightestimatedSectionHeaderHeightestimatedSectionFooterHeight 預設都是開啟的。真是令人驚喜。

@property (nonatomic) CGFloat rowHeight;             // default is UITableViewAutomaticDimension
@property (nonatomic) CGFloat sectionHeaderHeight;   // default is UITableViewAutomaticDimension
@property (nonatomic) CGFloat sectionFooterHeight;   // default is UITableViewAutomaticDimension
@property (nonatomic) CGFloat estimatedRowHeight NS_AVAILABLE_IOS(7_0); // default is UITableViewAutomaticDimension, set to 0 to disable
@property (nonatomic) CGFloat estimatedSectionHeaderHeight NS_AVAILABLE_IOS(7_0); // default is UITableViewAutomaticDimension, set to 0 to disable
@property (nonatomic) CGFloat estimatedSectionFooterHeight NS_AVAILABLE_IOS(7_0); // default is UITableViewAutomaticDimension, set to 0 to disable
複製程式碼

踩坑1

在我們的app中,首頁的 UITableView 列表是手動計算的行高,突然出現了以往只有開啟自動計算行高才會出現的滾動條跳動的現象,給 TableViewcontentSize 加了observer,果然一直在變。然後在這裡找到了原因。

踩坑2 (更新)

在使用 MJRefersh 的時候,本身程式碼存在一個 bug,原來並沒有發現,iOS 11 幫我發現了這個問題。

// tableView 設定
let footer = MJRefreshAutoFooter(refreshingBlock: {  [weak self] in
    if let strongSelf = self {
        if let block = strongSelf.footerBlock {
            block()
        }
    }
})
footer?.triggerAutomaticallyRefreshPercent = -20
tableView.mj_footer = footer

// 請求結束後處理(錯誤)
models.append(requestModels)
if models.count < pageSize { // 這裡是個bug
    tableView.mj_footer.endRefreshingWithNoMoreData()
} else {
    tableView.mj_footer.state = .idle
}
tableView.reloadData()

// 請求結束後處理(正確)
if requestModels.count < pageSize { // 修復bug
    tableView.mj_footer.endRefreshingWithNoMoreData()
} else {
    tableView.mj_footer.state = .idle
}
models.append(requestModels)
tableView.reloadData()
複製程式碼

上面程式碼中,在 iOS 11 之前也存在隱含的問題,就是 tableView footer 一直不能被標記為 無更多資料 的狀態,即使沒有資料了,使用者下拉依然後發起請求。 在 iOS 11 中,由於估算行高,互動到底部時,依然會觸發 tableViewcontentSizecontentOffset 變化,同時會觸發 refreshingBlock, 和 tableViewreloadData,導致了最後一頁資料陷入了迴圈請求。

引申問題 如果存在使用監聽 tableViewcontentSizecontentOffset 變化來觸發的一些事件,最好把 tableView 的自動計算行高關掉,以免出現問題。

三、iPhone X***(嚴重)***

1. 狀態列獲取網路狀態

眾所周知,iPhone X多了個“美美的”劉海,它的狀態列發生了變化。這也導致了原來從狀態列檢視獲取網路狀態的API出了問題,會導致閃退。

// 獲取當前app狀態列子檢視
UIApplication *app = [UIApplication sharedApplication];
NSArray *children = [[[app valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews];
int type = 0;
for (id child in children) {
    if ([child isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
        type = [[child valueForKeyPath:@"dataNetworkType"] intValue];
    }
}

switch (type) {
    case 1:
        return @"2G";
    case 2:
        return @"3G";
    case 3:
        return @"4G";
    case 5:
        return @"WIFI";
    default:
        return @"Unknow";
        break;
}
複製程式碼

不過你依然可以用AFNetworking類似的方式,獲取網路狀態:

SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL};
SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context);
SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);

switch (self.networkReachabilityAssociation) {
    case AFNetworkReachabilityForName:
        break;
    case AFNetworkReachabilityForAddress:
    case AFNetworkReachabilityForAddressPair:
    default: {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{
            SCNetworkReachabilityFlags flags;
            SCNetworkReachabilityGetFlags(self.networkReachability, &flags);
            AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags);
            dispatch_async(dispatch_get_main_queue(), ^{
                callback(status);

                NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
                [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:@{ AFNetworkingReachabilityNotificationStatusItem: @(status) }];


            });
        });
    }
        break;
}

static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) {
    BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0);
    BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0);
    BOOL canConnectionAutomatically = (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0));
    BOOL canConnectWithoutUserInteraction = (canConnectionAutomatically && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0);
    BOOL isNetworkReachable = (isReachable && (!needsConnection || canConnectWithoutUserInteraction));

    AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown;
    if (isNetworkReachable == NO) {
        status = AFNetworkReachabilityStatusNotReachable;
    }
#if	TARGET_OS_IPHONE
    else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0) {
        status = AFNetworkReachabilityStatusReachableViaWWAN;
    }
#endif
    else {
        status = AFNetworkReachabilityStatusReachableViaWiFi;
    }

    return status;
}
複製程式碼

2.狀態列

  1. 狀態列高度由原來的20,變為44了,以前使用常量的就被坑了。
  2. 在修改我們的巨集過程中遇到了另外一個坑,特此提醒:
// 原有
#define MPStatusBarHeight (20)
// 新的
#define MPStatusBarHeight (UIApplication.sharedApplication.statusBarFrame.size.height)

/* 坑在此處 */
// application 的 statusBarFrame 在隱藏狀態列的時候是 CGRectZero
@property(nonatomic,readonly) CGRect statusBarFrame __TVOS_PROHIBITED; // returns CGRectZero if the status bar is hidden
複製程式碼

3.友盟分享

友盟分享 SDK 6.4.6 版本提供的介面沒有適配 iPhone X 需要更新 SDK 到最新的 6.8.0 版本,很遺憾的是,目前最新的友盟所有產品都沒有提供 cocoapods 版本,需要手動整合。 在整合過程中遇到一個坑: 由於我們工程同時使用 pod 引用了友盟分享和友盟統計,本來只想升級友盟分享,於是直接跳到整合友盟分享的文件部分,執行了下面的操作:

1、移除pod對 UMShare的引用,執行 pod install
2、新增UMShareSDK到工程
3、修改檔案引用錯誤
4、清除DerivedData
5、在模擬器build
複製程式碼

報錯:

image.png

詢問了友盟客服(馬上就回復了,很給力),是由於沒有整合 common 基礎庫,回過頭來看文件,發現整合友盟任意庫都需要加入 common 基礎庫。 但是一旦加入 common 基礎庫,又會和使用 pod 引用的友盟統計衝突,無奈,只能統計庫和分享庫都換成手動引用。

四、UIToolBar

UIToolBar 中兩側新增了 UIBarButtonItem,在 iOS 11 之前會佈局在邊,在 iOS 11 中兩個item是緊挨著的,需要在中間新增 UIBarButtonSystemItemFlexibleSpace 型別的 item 才可以。

五、ALAssetsLibrary 儲存圖片閃退

在 iOS 11 之前,你可以直接使用下面程式碼來儲存圖片到相簿:

#import <AssetsLibrary/AssetsLibrary.h>
// ALAssetsLibrary
[[[ALAssetsLibrary alloc] init] writeImageDataToSavedPhotosAlbum:imageData metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) {
    [self saveResultWithResult:(error == nil)];
}];
複製程式碼

在 iOS 11中則會直接崩潰,儲存圖片的新姿勢:

  • 解決方案1: 在 infoPlist 檔案中追加相簿寫入許可權的提示
引數 key Xcode name 版本 說明
NSPhotoLibraryAddUsageDescription "Privacy - Photo Library Additions Usage Description" Specifies the reason for your app to get write-only access to the user’s photo library. See NSPhotoLibraryAddUsageDescription for details. iOS 11 and later 本引數iOS 11必須追加
NSPhotoLibraryUsageDescription “Privacy - Photo Library Usage Description” Specifies the reason for your app to access the user’s photo library. See NSPhotoLibraryUsageDescription for details. iOS 6.0 and later 本引數iOS 10以後必須追加

在infoPlist中直接新增(xcode 中 open as Source Code):

<key>NSPhotoLibraryUsageDescription</key>
<string>此 App 需要您的同意才能讀取媒體資料庫</string>
<key>NSPhotoLibraryAddUsageDescription</key>
<string>此 App 需要您的同意才能寫入媒體資料庫</string>
複製程式碼
  • 解決方案2: 如果沒有按方案1新增寫入許可權提示,ALAssetsLibrary 寫入直接崩潰,而 PHPhotoLibrary 儲存圖片會直接觸發向使用者請求相簿寫入許可權的 Alert 提示。
#import <Photos/Photos.h>
// PHPhotoLibrary
- (void)saveImageByPHPhotoLibrary:(UIImage *)image {
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        [PHAssetCreationRequest creationRequestForAssetFromImage:image];
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self saveResultWithResult:(success && error == nil)];
        });
    }];
}
複製程式碼

更新

由於在應用中使用了 WKWebView , WKWebView 在沒有處理的情況下,長按圖片會彈出儲存圖片的選項,選擇儲存圖片同樣會崩潰。所以該方案不能處理好所有入口,推薦使用方案1。

image.png

六、鍵盤鑰匙串 (password auto fill)

1、問題

在iOS 11系統中,你會發現你原本的一些輸入框喚起系統鍵盤後出現如下的狀況:

image.png

鍵盤右上角的?,是iOS 11的新特性 Password Auto Fill,假如你在程式碼中設定 UITextField 的 contentType 為 usernamepassword型別,就會出現上面的圖示。

usernameTextField.textContentType = UITextContentType.username
passwordTextField.textContentType = UITextContentType.password
複製程式碼

而有些情況,在 XIB 檔案中,如果你沒有指定特定型別,鍵盤也會出現?:

image.png

對應情況你只需要將 contentType 設定為其它型別即可:

image.png

2、關於 Password Auto Fill

Password Auto Fill 的適配可以參考iOS 11 ---- Password Auto Fill (PS: 感覺機制有點類似UniversalLink)

七、react-native

可以參考下面程式碼,來適配狀態列和底部安全域:

import { Dimensions, Platform } from 'react-native'

const { width, height } = Dimensions.get('window')

export const isIphoneX = () => (
    Platform.OS === 'ios' &&
    !Platform.isPad &&
    !Platform.isTVOS &&
    (height === 812 || width === 812)
)

const getStatusBarHeight = () => {
  if (Platform.OS === 'android') {
    return 0
  }

  if (isIphoneX()) {
    return 44
  }

  return 20
}

// const
export const IPHONEX_BOTTOM_HEIGHT = 34
export const STATUSBAR_HEIGHT = getStatusBarHeight()
複製程式碼

相關文章