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

时间:2016-11-05 16:12:19

标签: ios swift swift3 uiimagepickercontroller

在我的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上显示图像 - 那么我该如何处理相机输出呢?

1 个答案:

答案 0 :(得分:2)

let imageUrl = info[UIImagePickerControllerReferenceURL] as! NSURL
     

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

你错了。你不需要它,并且要求它是没有意义的,因为根据定义,这个图像不在照片库中 - 它没有参考URL。

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

(事实上,您很可能永远不会一直使用UIImagePickerControllerReferenceURL进行任何操作,因为您在两个案件中都获得了UIImagePickerControllerOriginalImage是您在图像视图中显示目的时应使用的图像。)