Fabian Boulegue February 2016

UIImagePickerController get Image URL with Swift

I have a UIImagePickerController to let the user select a image, as i want to upload this image i would need the image "localURL". Is there a way to get this localURL from my picker.

@IBOutlet weak var imageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    imagePicker.delegate = self
}

@IBAction func loadImageButtonTapped(sender: AnyObject) {
    imagePicker.allowsEditing = false
    imagePicker.sourceType = .PhotoLibrary
    presentViewController(imagePicker, animated: true, completion: nil)
}


func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        imageView.contentMode = .ScaleAspectFit
        imageView.image = pickedImage
    }

    dismissViewControllerAnimated(true, completion: nil)
}


func imagePickerControllerDidCancel(picker: UIImagePickerController) {
    dismissViewControllerAnimated(true, completion: nil)
}

Answers


MarkHim February 2016

You won't get any local url since you don't have access to images outside of your app container.

You don't need the file for transmitting the image, NSData should be perfectly fine. I suggest you transform it to NSData like this

let imageData: NSData = UIImagePNGRepresentation(pickedImage)

Update: as i said, you won't have access to the actual file. The only way to have the image as file is to store it yourself.

in your update you showed some code for persisting the image yourself, which makes sense. It will be more performant if you use the ’pickedImage’ when setting your ’imageView.image’ instead of writing the image file and reading it, transforming it to an ’UIImage’ and then setting it as ’imageView.image’

I still havent really figured out, why you need the image as file and not simply send the ’NSData’ to your server. Maybe that is an option worth considering for you


Fabian Boulegue February 2016

as work around i do save the image,

  if let data = UIImageJPEGRepresentation(pickedImage, 0.8) {
                let filename = getDocumentsDirectory().stringByAppendingPathComponent("image.jpg")
                data.writeToFile(filename, atomically: true)
                print("file saved as image.jpg")
                print(filename)

                var image = UIImage(contentsOfFile: filename)
                imageView.image = image

            }

Post Status

Asked in February 2016
Viewed 1,233 times
Voted 6
Answered 2 times

Search




Leave an answer