【问题标题】:UIImagePickerController must be used from main thread only | app crashUIImagePickerController 只能在主线程中使用 |应用程序崩溃
【发布时间】:2020-10-27 16:18:02
【问题描述】:

大家好,我正在 iOS 14 中实现 UIImagePickerController。当用户选择相机时,当用户同意使用相机时,我的应用程序崩溃,在 xcode 上以紫色返回此错误

- [UIImagePickerController init] must be used from main thread only

我该如何解决这个问题? 谢谢大家的建议

private func cameraAuth(auth sourceType: UIImagePickerController.SourceType) {
    switch AVCaptureDevice.authorizationStatus(for: .video) {
    case .denied: imagePickerAuthDenied()
    case .restricted: imagePickerAuthRestricted()
    case .authorized: showImagePicker(sourceType: sourceType)
   
    case .notDetermined:

        AVCaptureDevice.requestAccess(for: .video) { (success) in
            if success { self.showImagePicker(sourceType: sourceType) }
            else { self.imagePickerAuthDenied() }
        }
        
    default : print("Default Switch Camera Auth")
    }
}

private func showImagePicker(sourceType: UIImagePickerController.SourceType) {
   
    let imagePickerController = UIImagePickerController()
    imagePickerController.delegate = self
    imagePickerController.sourceType = sourceType
    imagePickerController.allowsEditing = true
    present(imagePickerController, animated: true, completion: nil)
}

【问题讨论】:

  • 为了澄清,任何与 UI 相关的事情(修改 UI 等)都应该只在主线程上完成。

标签: ios swift xcode uiimagepickercontroller


【解决方案1】:

您需要将代码包装在authorizationStatus/AVCaptureDevice.requestAccess(for: .video) { (success) in 中的 DispatchQueue.main.async

AVCaptureDevice.authorizationStatus(for: .video) {
   DispatchQueue.main.async {
     ///
   }
}

AVCaptureDevice.requestAccess(for: .video) { (success) in 
   DispatchQueue.main.async {
     ///
   }
}

【讨论】:

  • 您在我们的答案中有一个奇怪的重复代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-29
  • 1970-01-01
相关资源
最近更新 更多