从相机获取照片时,imagePickerController 崩溃。从照片库工作正常。为什么?

imagePickerController crashes when fetching photos from camera. From photo library works fine. Why?

在我的 swift 应用程序中,我允许用户添加照片 - 来自相机或照片库。他有一个选择:

@IBAction func captureImage(_ sender: AnyObject) {

    let imageFromSource = UIImagePickerController()
    imageFromSource.delegate = self
    imageFromSource.allowsEditing = false

    let alertController = UIAlertController(
        title: "What exactly do you want to do?",
        message: "Choose your action.",
        preferredStyle: .actionSheet)

    let selectPictureAction = UIAlertAction(
        title: "Choose image from gallery",
        style: .default) { (action) -> Void in

            imageFromSource.sourceType = UIImagePickerControllerSourceType.photoLibrary
            self.present(imageFromSource, animated: true, completion: nil)
    }
    alertController.addAction(selectPictureAction)

    let captureFromCamera = UIAlertAction(
    title: "Capture photo from camera",
    style: .default) { (action) -> Void in
        imageFromSource.sourceType = UIImagePickerControllerSourceType.camera   
        self.present(imageFromSource, animated: true, completion: nil)   
    }
    alertController.addAction(captureFromCamera)
}

然后我有一个函数:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

    let imageUrl          = info[UIImagePickerControllerReferenceURL] as! NSURL
    let imageName         = imageUrl.lastPathComponent
    let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
    let photoURL          = NSURL(fileURLWithPath: documentDirectory)
    let localPath         = photoURL.appendingPathComponent(imageName!)
    let image             = info[UIImagePickerControllerOriginalImage]as! UIImage
    let data              = UIImagePNGRepresentation(image)
    do
    {
        try data?.write(to: localPath!, options: Data.WritingOptions.atomic)
    }
    catch
    {
        // Catch exception here and act accordingly

    }
    self.dismiss(animated: true, completion: {})

    imageView.image = image
    .
    .
    .

当用户从图库中选择图片时 - 一切正常,但当用户拍照时 - 我的应用程序在这一行崩溃:

let imageUrl          = info[UIImagePickerControllerReferenceURL] as! NSURL

出现错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

我需要此 imageUrl 稍后在 imageView 上显示图像 - 那么我如何处理此处的相机输出?

let imageUrl = info[UIImagePickerControllerReferenceURL] as! NSURL

I need this imageUrl to display the image later on imageView - so how can I handle the camera output here?

你错了。你不需要它,要求它也没有意义,因为根据定义,这张图片不在照片库中——它没有参考 URL。

在这种情况下你想要的密钥是UIImagePickerControllerOriginalImage

(事实上,很可能你 永远不会 一直在使用 UIImagePickerControllerReferenceURL 做任何事情,因为你在 [=21= 中得到了 UIImagePickerControllerOriginalImage ]两种种情况。如果您的目的是在图像视图中显示,那么就是您应该使用的图像。)