這個警告我自己也撞過,翻了一大圈資料才摸到真正的癥結,乾脆整理成一篇筆記,說不定能幫到同樣卡住的人。
警告原文:Snapshotting a view that has not been rendered results in an empty snapshot. Ensure your view has been rendered at least once before snapshotting or snapshot after screen updates.
問題現象:在 iOS 8 上呼叫系統相機時,畫面會先卡住一兩秒,之後才跳出 UIImagePickerController;同一份程式碼放到 iOS 7 上卻順暢無比。網路上能搜到的招數五花八門——有人說要把 imagePickerController 宣告成全域變數,有人建議延遲 0.5 秒再 present,試下來全都無效。後來我單獨開了一個 Demo 專門追這個問題,才終於有了突破。
關鍵其實不在相機控制器身上,而在 presentViewController 這個動作本身。翻一下 UIViewController 的宣告就能看到:
@property(nonatomic,assign) UIModalPresentationStyle modalPresentationStyle NS_AVAILABLE_IOS(3_2);
這是一個枚舉值。iOS 7 的 SDK 中定義如下:
typedefNS_ENUM(NSInteger, UIModalPresentationStyle) { UIModalPresentationFullScreen = 0, #if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_3_2 UIModalPresentationPageSheet, UIModalPresentationFormSheet, UIModalPresentationCurrentContext, #endif #if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_7_0 UIModalPresentationCustom, UIModalPresentationNone = -1, #endif };
到了 iOS 8 的 SDK,這個枚舉多了幾個成員:
typedefNS_ENUM(NSInteger, UIModalPresentationStyle) { UIModalPresentationFullScreen = 0, UIModalPresentationPageSheetNS_ENUM_AVAILABLE_IOS(3_2), UIModalPresentationFormSheetNS_ENUM_AVAILABLE_IOS(3_2), UIModalPresentationCurrentContextNS_ENUM_AVAILABLE_IOS(3_2), UIModalPresentationCustomNS_ENUM_AVAILABLE_IOS(7_0), UIModalPresentationOverFullScreenNS_ENUM_AVAILABLE_IOS(8_0), UIModalPresentationOverCurrentContextNS_ENUM_AVAILABLE_IOS(8_0), UIModalPresentationPopoverNS_ENUM_AVAILABLE_IOS(8_0), UIModalPresentationNoneNS_ENUM_AVAILABLE_IOS(7_0) = -1, };
答案就藏在這裡:iOS 8 新增了 UIModalPresentationOverCurrentContext。只要在 iOS 8 以上把 modalPresentationStyle 設成這個值,卡頓和警告就會一起消失。
if([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0) { self.modalPresentationStyle=UIModalPresentationOverCurrentContext; }
寫到這裡,這個困擾我好幾天的問題總算收尾了。如果你也遇到同樣的警告,不妨先檢查一下 modalPresentationStyle,多數情況下不必去動相機相關的程式碼。