相机、相册权限请求问题

2019-02-23  本文已影响7人  小五92

问题:

在调用相机时,进行了权限请求,发生了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(), ^{
});
上一篇下一篇

猜你喜欢

热点阅读