Mhmd Backer Shehadi
Mhmd Backer Shehadi

Reputation: 589

Getting image path from the iPhone camera Using UIImagePickerController return nil

I am trying to get the image path from camera using UIImagePickerController

here is the code :

 @IBAction func takePhoto(sender: UIButton) {
        imagePicker =  UIImagePickerController()
        imagePicker?.allowsEditing = true
        imagePicker?.delegate = self
        imagePicker?.sourceType = .Camera

        presentViewController(imagePicker!, animated: true, completion: nil)
    }

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        let imageURL = info[UIImagePickerControllerReferenceURL] as? NSURL
        print(" Path \(imageURL)")
        imageView?.contentMode = .ScaleAspectFit
        imageView?.image = info[UIImagePickerControllerOriginalImage] as?        UIImage
        imagePicker?.dismissViewControllerAnimated(true, completion: nil)
    }

any help ?

Upvotes: 2

Views: 5327

Answers (2)

knig_T
knig_T

Reputation: 2044

I use this method to save the image taken via camera

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    print(info)
    var selectedImage: UIImage!
    if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
        selectedImage = image
    } else if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
        selectedImage = image
    }
    self.profileImageView.image = selectedImage

    if (picker.sourceType == UIImagePickerControllerSourceType.camera) {

        let imgName = UUID().uuidString
        let documentDirectory = NSTemporaryDirectory()
        let localPath = documentDirectory.appending(imgName)

        let data = UIImageJPEGRepresentation(selectedImage, 0.3)! as NSData
        data.write(toFile: localPath, atomically: true)
        let photoURL = URL.init(fileURLWithPath: localPath)


    }
}

Upvotes: 14

Abhinav
Abhinav

Reputation: 38142

Delegate didFinishPickingMediaWithInfo gets called after a pic is taken using the camera. UIImagePickerControllerReferenceURL object will be nil as the image has not been saved to the camera roll yet.

To get rid of this situation, you need to first save the image and then use the url of the path you saved. You can however use UIImagePickerControllerOriginalImage property on info to show the taken image in your application. Hope this helps!

Upvotes: 4

Related Questions