Reputation: 247
I'm using UIImagePickerController
to pick image i want path of selected image but I can't get it.
what I'm trying in code:
func handleImg() {
let picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = true
present(picker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
var selectedImageFromPicer : UIImage?
if let editedImage = info["UIImagePickerControllerEditedImage"] as? UIImage {
selectedImageFromPicer = editedImage
} else if let originalImage = info["UIImagePickerControllerOriginalImage"] as? UIImage {
selectedImageFromPicer = originalImage
}
if let selectedImage = selectedImageFromPicer {
img.image = selectedImage
}
if let imageURL = info[UIImagePickerControllerReferenceURL] as? URL {
let result = PHAsset.fetchAssets(withALAssetURLs: [imageURL], options: nil)
let asset = result.firstObject
var imgStr = asset?.value(forKey: "filename")
print(imgStr!)
}
dismiss(animated: true, completion: nil)
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
print("canceled picker")
dismiss(animated: true, completion: nil)
}
}
By above code I can only get the name of image. I want path of image.
Upvotes: 0
Views: 1135
Reputation: 4659
If you print the info
object you will see all available keys for accessing the values of this dictionary. The image path key is UIImagePickerControllerImageURL
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
guard let imageUrl = info["UIImagePickerControllerImageURL"] as? URL else {
return
}
print(imageUrl.path) // prints the path
picker.dismiss(animated: true, completion: nil)
}
Upvotes: 2
Reputation: 1526
Following code may help you in get the image path.
Code to show UIImagePickerController.
@IBAction func showPicker(_ sender: Any) {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = UIImagePickerControllerSourceType.savedPhotosAlbum
picker.allowsEditing = false
present(picker, animated: true, completion: nil)
}
Delegate method didFinishPickingMediaWithInfo.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let imageUrl = info[UIImagePickerControllerReferenceURL] as! NSURL
let imageName = imageUrl.lastPathComponent
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let photoURL = NSURL(fileURLWithPath: documentDirectory)
let localPath = photoURL.appendingPathComponent(imageName!)
//Check these values
self.dismiss(animated: true, completion: nil);
}
Upvotes: 1