Sam Shaikh
Sam Shaikh

Reputation: 1646

How to get URL of image of Image Gallery iOS Swift?

I am coding as below for UIImagePickerController to get image from the photo library.

if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
    // Code here

    var imagePicker = UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary;
    imagePicker.mediaTypes = [kUTTypeImage]
    imagePicker.allowsEditing = false

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

After selecting an image, I can show it on UIImageView, but I cannot get it's URL.

This is code I wrote to get it.

let url: NSString = info[UIImagePickerControllerReferenceURL] as NSString

var imageName:String = url.lastPathComponent        
println("URL is \(imageName)")

let image = info[UIImagePickerControllerOriginalImage] as UIImage
profileImage.image =  image
self.dismissViewControllerAnimated(true, completion: nil)

Here it gives nil and if I use UIImagePickerControllerEditedImage, it also crashes.

Can't we access URL directly, if not what is UIImagePickerControllerReferenceURL supposed to return?

How can I get the URL of the image so it could be sent to the server.

Thanks

Upvotes: 1

Views: 4261

Answers (1)

Alvin George
Alvin George

Reputation: 14294

let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask    = NSSearchPathDomainMask.UserDomainMask

if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) {
    if paths.count > 0 {
        if let dirPath = paths[0] as? String {
            let readPath = dirPath.stringByAppendingPathComponent("yourNameImg.png")
            var pickedimage = UIImage(CGImage: UIImage(contentsOfFile: readPath)!.CGImage, scale: 1.0, orientation: .Up)

            UploadImagePreview.image = pickedimage
        }
    }
}

Note: We can set the image from url if the complete address is known. Here we are searching for the given image name in nsDocumentDirectory , finds out the complete image path and then set to image view.

Upvotes: 1

Related Questions