Giorgio Antonioli
Giorgio Antonioli

Reputation: 16214

Swift UIImagePickerController dynamic cast failed in getting path

i'm trying to get the path of a photo from UIImagePicker and i'm getting "Swift dynamic cast failed" when i try to get it. Here is my code:

@IBAction func addPhotoButton(sender: AnyObject) {
    if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.SavedPhotosAlbum){

        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum;
        imagePicker.allowsEditing = true

        self.presentViewController(imagePicker, animated: true, completion: nil)
    }
}

And here where i get the path:

func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!){
    self.dismissViewControllerAnimated(true, completion: { () -> Void in
        var path: NSURL = editingInfo.valueForKeyPath("UIImagePickerControllerOriginalImage") as NSURL
        println(path)
    })
}

The app crashes when i try to get the value of the var path

Upvotes: 0

Views: 706

Answers (1)

Midhun MP
Midhun MP

Reputation: 107141

The UIImagePickerControllerOriginalImage key will return an UIImage not the NSURL of that chosen image.

If you need the referece url, you need to use UIImagePickerControllerReferenceURL key.

Change your following code:

var path: NSURL = editingInfo.valueForKeyPath("UIImagePickerControllerOriginalImage") as NSURL

to:

var path: NSURL = editingInfo.valueForKey("UIImagePickerControllerReferenceURL") as NSURL

UIImagePickerControllerOriginalImage

Specifies the original, uncropped image selected by the user.

The value for this key is a UIImage object.


UIImagePickerControllerReferenceURL

The Assets Library URL for the original version of the picked item.

After the user edits a picked item—such as by cropping an image or trimming a movie—the URL continues to point to the original version of the picked item.

The value for this key is an NSURL object.

Reference UIImagePickerControllerDelegate Protocol Reference

Upvotes: 2

Related Questions