1

I am working with images for the first time and I have been able to select an image and display it on the page. My question is how can I get the name of the image selected ? I been searching around but have not been able to find it . This code below fires every time you select an image

 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
    {

        photoImageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
        self.dismiss(animated: false, completion: nil)
        let FileName = " Image Name of selected file"
    }

where the photoImageView is

var photoImageView = UIImageView(frame: CGRect(x: 82,y: 300,width: 100,height: 100))

a small ImageView that displays the selected image, I would like to get the FileName now any suggestions would be great

nsinvocation
  • 7,559
  • 3
  • 41
  • 46
user1949387
  • 1,245
  • 3
  • 21
  • 38
  • 3
    Please [search](http://stackoverflow.com/search?q=uiimagepickercontroller+image+name) before posting. – rmaddy Jan 10 '17 at 22:03

4 Answers4

4

Short answer: You can't. The system doesn't give you the user's name for the file. I remember puzzling about this as well.

As I recall what it gives you is a pointer to an in-memory UIImage object, not even a URL to a system-named file on disk. (But it's been a while since I've used the image picker.)

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • 1
    Not quite. You can get the URL for an image selected from the photo library. That URL will of course have a filename as part of the URL. It's not really a meaningful filename but you can get it if really needed. – rmaddy Jan 10 '17 at 22:11
  • @rmaddy, thanks for the correction. I couldn't remember for sure. In any case you can't get a *meaningful* filename... – Duncan C Jan 10 '17 at 22:49
0

Using Photos API (PHAsset & PHAssetResource) you can get file name of the image selected using UIImagePickerController. I posted the solution in this question.

Yaiba
  • 571
  • 7
  • 14
0

From iOS 11.0 onwards they introduced a new key into info dictionary to get PHAsset of picked image , you can try this:

func imagePickerController(_ picker: UIImagePickerController,didFinishPickingMediaWithInfo info: [String : Any]) {
if let photoAsset = info[UIImagePickerControllerPHAsset] as? PHAsset {
  if let fileName = photoAsset.value(forKey: "filename") ?? "nonamefound"}
CodeDev
  • 13
  • 5
-1

You can use write this code in your delegate function for fetching the image name from the picker.

func imagePickerController(_ picker: UIImagePickerController, 
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : 
Any]) {
   
        picker.dismiss(animated: true, completion: nil)
    
        if let imgUrl = info[.imageURL] as? URL {
            let fileName = imgUrl.lastPathComponent
            print(fileName)
        }
    }