Swift - UIImagePickerController - how to use it?

user3806731 picture user3806731 · Jul 8, 2014 · Viewed 76.3k times · Source

I am trying hard to understand how this works, but it's pretty hard for me. =) I have 1 view, there is one button and one small ImageView area for preview. The button triggers imagepickercontroller, and the UIView will display picked image. There is no error but the image doesn't show in the UIImageView area.

var imagePicker = UIImagePickerController()
@IBOutlet var imagePreview : UIImageView

@IBAction func AddImageButton(sender : AnyObject) {
    imagePicker.modalPresentationStyle = UIModalPresentationStyle.CurrentContext
    imagePicker.delegate = self
    self.presentModalViewController(imagePicker, animated: true)

}
func imagePickerController(picker: UIImagePickerController!, didFinishPickingMediaWithInfo info:NSDictionary!) {
    var tempImage:UIImage = info[UIImagePickerControllerOriginalImage] as UIImage
    imagePreview.image  = tempImage

    self.dismissModalViewControllerAnimated(true)

}

func imagePickerControllerDidCancel(picker: UIImagePickerController!) {

    self.dismissModalViewControllerAnimated(true)
}

Answer

Jesper picture Jesper · Jul 8, 2014

You're grabbing a UIImage named UIImagePickerControllerOriginalImage and there exists no such image. You're meant to grab the UIImage with the key UIImagePickerControllerOriginalImage from the editingInfo dictionary:

let tempImage = editingInfo[UIImagePickerControllerOriginalImage] as! UIImage