Search code examples
iosswiftxcodeuiimagepickercontroller

UIImagePickerController must be used from main thread only | app crash


Hi everyone I am implementing UIImagePickerController in iOS 14. When the user selects the camera my app crashes when the user agrees to use the camera, returning this error in purple on xcode

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

How can I solve this problem? thanks everyone for the advice

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)
}

enter image description here


Solution

  • You need to wrap code inside authorizationStatus/AVCaptureDevice.requestAccess(for: .video) { (success) in in DispatchQueue.main.async

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

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