Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get filename when using PHPickerViewController for photo

Tags:

swift

swift3

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

like image 416
Sittipong Wiangwaeng Avatar asked Jan 27 '26 00:01

Sittipong Wiangwaeng


2 Answers

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)
}
like image 177
Faysal Ahmed Avatar answered Jan 28 '26 21:01

Faysal Ahmed


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{
   
            }
        }
    }
}
like image 25
re_zacks Avatar answered Jan 28 '26 23:01

re_zacks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!