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

iOS 11 - always opens photo library even the source type change it from .photoLibrary to .camera

代码在 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)
}
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)

    }

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

我发现问题了。

主要内容:您必须在呈现 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
}

P.S。检查并处理 Xcode 9 GM