首页 > 解决方案 > 仅在 iPhone X (iOS 12) 上的横向模式下使用 UIImagePickerController 崩溃的应用程序

问题描述

在 Xcode 10.1 中创建的项目仅具有设备方向横向左侧和右侧。

在 Plist 中添加了以下键

隐私 - 相机使用说明: “用于拍照”</p>

   import UIKit

class UploadViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate

{
    //MARK:- ViewDidLoad
    override func viewDidLoad() {
        super.viewDidLoad()


    }

 @IBAction func cameraButtonAction(_ sender: UIButton)
    {

        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera){

            let imagePicker = UIImagePickerController()
            imagePicker.sourceType = .camera
            imagePicker.modalPresentationStyle = .overCurrentContext
            imagePicker.delegate =  self
            self.present(imagePicker, animated: true, completion: nil)

        }else{

            let alert  = UIAlertController(title: "Warning", message: "You don't have camera", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            self.present(alert, animated: true, completion: nil)

        }
    }

}

以上代码在以下设备中运行良好

iPhone 8 (iOS 12)

iPhone 7 (iOS 11.4.1)

iPad 迷你 (iOS 11)

但是当我在 iOS 12.1 的 iPhoneX 中运行它时,会出现以下错误。

Terminating app due to uncaught exception 'UIApplicationInvalidInterfaceOrientation', reason: 'Supported orientations has no common orientation with the application, and [CAMViewfinderViewController shouldAutorotate] is returning YES'
*** First throw call stack:

libc++abi.dylib: terminating with uncaught exception of type NSException

我对这个问题进行了研究,但我还没有找到解决方案。以下是我为相关问题找到的几个链接,但没有一个适用于 iPhoneX 的答案。

横向使用 UIImagePickerController

UIImagePickerController 接口方向崩溃

https://www.reddit.com/r/iOSProgramming/comments/3xpwot/discussion_lets_talk_about_landscape_cameras/

标签: iosiphoneswiftiphone-xios12

解决方案


长期以来,我也面临着这个问题,并在做了这么多 RND 之后找到了解决方案:

第 1 步:制作自定义 UIImage 选择器控制器并使用它。相同的代码如下

class MyImagePickerViewController: UIImagePickerController {

    override public func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    override public var shouldAutorotate: Bool {
        return false
    }

    override public var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return UIInterfaceOrientationMask.landscape // Since your app is in only landscape mode
    }

}

第 2 步:制作一个全局标志 isOpenGallery 并在打开画廊之前将其设为真,并在关闭 MyImagepickercontroller 之前将其设为假,并在您的 App Delegate 中实现以下代码:

  func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    return isOpenGallery ? UIInterfaceOrientationMask.portrait : UIInterfaceOrientationMask.landscape
}

推荐阅读