3

How to get filename when using PHPickerViewController for photo

this is my function code

func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
        
        dismiss(animated: true, completion: nil)
        
        for item in results {
            item.itemProvider.loadObject(ofClass: UIImage.self) {(image, error) in
                if let image = image as? UIImage{

   
                }
                
            }
        }
    }

Please help, thank you

2 Answers 2

8

Hope you van find file name by using this:

item.itemProvider.loadFileRepresentation(forTypeIdentifier: "public.item") { (url, error) in
                if error != nil {
                   print("error \(error!)");
                } else {
                    if let url = url {
                        let filename = url.lastPathComponent;
                        print(filename)
                    }
                }
            }

You can use this to get file name from UIImagePickerController

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let imageURL = info[UIImagePickerControllerReferenceURL] as? URL {
        let result = PHAsset.fetchAssets(withALAssetURLs: [imageURL], options: nil)
        let asset = result.firstObject
        print(asset?.value(forKey: "filename"))

    }

    dismiss(animated: true, completion: nil)
}
Sign up to request clarification or add additional context in comments.

5 Comments

Many thanks for your gratitude ,but I change if error == nil to if error != nil it work and give filename finally.
No problem you can use that also.
Sorry i have 1 question.if i using UIImagePickerController how to get filename like PHPickerViewController.
@SittipongWiangwaeng please check the updated answer.
i was looking for something else but this answer solve my 2 problems. Thanks @FaysalAhmed
4

The NSItemProvider from PHPickerResult has a suggestedName property that will give you the file name. So from your provided code:

func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
        
    dismiss(animated: true, completion: nil)
        
    for item in results {
        item.itemProvider.loadObject(ofClass: UIImage.self) {(image, error) in
            // This will give you the file name
            guard let fileName = item.itemProvider.suggestedName else { return }
            if let image = image as? UIImage{
   
            }
        }
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.