iOS 11 - 始终打开照片库,即使源类型也从.photoLibrary更改为.camera

Moh*_*ham 5 uiimagepickercontroller ios11 xcode9-beta

该代码在iOS 10及更低版本中完美运行.但是,在iOS 11取消照片库并打开相机后,它总是打开照片库.这只发生在iOS 11中.

代码在Xcode 9 Beta 4中编译.

代码如下:

@IBAction func buttonProfilePicPressed(_ sender: UIButton)
{
    let alert = UIAlertController(title: "Choose Image", message: nil, preferredStyle: .actionSheet)
    alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: { _ in
        self.openCamera()
    }))

    alert.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { _ in
        self.openGallary()
    }))

    alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil))

    self.present(alert, animated: true, completion: nil)
    imgPicker.delegate = self
    self.present(imgPicker, animated: true, completion: nil)
}

func openCamera()
{
    if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.camera))
    {
        imgPicker.sourceType = UIImagePickerControllerSourceType.camera
        imgPicker.allowsEditing = true
        self.present(imgPicker, 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)
    }
}

func openGallary()
{
    imgPicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
    imgPicker.allowsEditing = true
    self.present(imgPicker, animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)

Vla*_*rin 5

我发现了什么是错的.

MAIN:您必须在呈现UIImagePickerController之前设置sourceType.关于这一点,您可以阅读文档UIImagePickerController.

是的,您可以看到sourceType的文档,但有关文档页面上的sourceType的信息对于iOS 11是错误的或不实际的.

结果:

  1. 首先,您必须配置UIImagePickerController
  2. 其次是介绍它.

在您的情况下,您只需要删除一行:

@IBAction func buttonProfilePicPressed(_ sender: UIButton)
{
    ...
    self.present(imgPicker, animated: true, completion: nil) //REMOVE IT!!!!!111
}
Run Code Online (Sandbox Code Playgroud)

PS检查并使用Xcode 9 GM


小智 3

func startCameraFromViewController(_ viewController: UIViewController, withDelegate delegate:
        UIImagePickerControllerDelegate & UINavigationControllerDelegate) -> Void {

        if (UIImagePickerController.isSourceTypeAvailable(.camera) == false) {
            print("fail")
        }

        let cameraController = UIImagePickerController()
        cameraController.sourceType = .camera
        cameraController.allowsEditing = true
        cameraController.delegate = delegate

        present(cameraController, animated: true, completion: nil)

    }
Run Code Online (Sandbox Code Playgroud)

这是适合我的代码。iOS 11 上也有同样的问题,但可以解决这个问题。也许你需要self.present(imgPicker, animated: true, completion: nil)buttonProfilePicPressed方法中删除。