Search code examples
swiftswift3

How to get filename when using PHPickerViewController for photo


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


Solution

  • 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)
    }