Search code examples
iosswiftswift4uiimagepickercontroller

Swift 4 didFinishPickingMediaWithInfo save image


I am using UIImagePickerController to use my camera like so:

@objc func toggle() {
        if UIImagePickerController.isSourceTypeAvailable(.camera) {

            //Define UIImagePickerController variable

            let imagePicker = UIImagePickerController()

            //Assign the delegate

            imagePicker.delegate = self

            //Set image picker source type

            imagePicker.sourceType = .camera

            //Allow Photo Editing

            imagePicker.allowsEditing = true

            //Present camera

            UIApplication.topViewController()?.present(imagePicker, animated: true, completion: nil)
        }
    }

Now I am trying to capture the image taken using the didFinishPickingMediaWithInfo method, I got this example online:

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

        let imageUrl          = info[UIImagePickerControllerOriginalImage] 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
        }

        UIApplication.topViewController()?.dismiss(animated: true, completion: nil);
    }

But I changed UIImagePickerControllerReferenceURL to UIImagePickerControllerOriginalImage as UIImagePickerControllerReferenceURL is nil. but after I change that I get this fatal error:

Could not cast value of type 'UIImage' (0x1b6b02b58) to 'NSURL'

How do I save the image take from the camera? What am I doing wrong?


Solution

  • Write your code as following this will give you image.

    let image = info[UIImagePickerControllerOriginalImage] as! UIImage
    

    UIImagePickerControllerOriginalImage return image not NSURL

    Write following code to get image url in iOS 11. From iOS 11 UIImagePickerControllerImageURL is available, earlier there are UIImagePickerControllerMediaURL key to get image url.

    if #available(iOS 11.0, *) {
        if let imageURL = info[UIImagePickerControllerImageURL] as? URL {
            print(imageURL)
        }
    } else {
        if let imageUrl = info[UIImagePickerControllerMediaURL] as? URL {
            print(imageUrl)
        }
    }
    

    I hope this will help you.