問題:
在調用相機時,進行了權限請求,發生了Crash。
原因:
在相機權限請求回調中,不在主線程,故喚起UIImagePickerController時發生崩潰。
分析:
1、相機的權限請求
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
//The completion handler is called on an arbitrary dispatch queue.
//It is the client's responsibility to ensure that any UIKit-related updates are called on the main queue or main thread as a result.
//意思是:completionHandler會在任意隊列上執行,我們要確保在主線程中執行。
}
But,爲什麼測試沒有測出來?因爲在已經授權時,這個handler會在主線程中執行;
那相冊權限呢?
2、相冊權限請求
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
//Photos may call your handler block on an arbitrary serial queue.
//If your handler needs to interact with UI elements, dispatch such work to the main queue.
//在官方api中的note敘述如上,可知,與相機類似。
}];
解決:
很簡單了,在回掉中,切到主線程中。
PS:附帶三種回主線程的方法。
參考:https://blog.csdn.net/cordova/article/details/54933729
// 1.NSThread
[self performSelectorOnMainThread:@selector(updateUI) withObject:nil waitUntilDone:NO];
- (void)updateUI {
}
// 2.NSOperationQueue
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
}];
// 3.GCD
dispatch_async(dispatch_get_main_queue(), ^{
});