User558
User558

Reputation: 1175

How to get image name from UIImagePickerControllerPHAsset taken with library or camera?

I want to get the file name from UIImagePickerControllerPHAsset in ios 11.0.3. unable to get picked image file name using this code. please help on this?

  if #available(iOS 11.0, *) {
                let asset = info[UIImagePickerControllerPHAsset] as? PHAsset
                fileName = ((asset?.value(forKey: "filename")) as? String)!
            } else {
                // Fallback on earlier versions
                let url = info[UIImagePickerControllerReferenceURL] as! URL
                let assets = PHAsset.fetchAssets(withALAssetURLs: [url], options: nil)
                fileName = PHAssetResource.assetResources(for: assets.firstObject!).first!.originalFilename
            }

Getting crashes on fileName = ((asset?.value(forKey: "filename")) as? String)!

Upvotes: 11

Views: 4104

Answers (3)

Mobi
Mobi

Reputation: 69

You can try this...

if #available(iOS 11.0, *) {
                let asset = info[UIImagePickerControllerPHAsset] as! PHAsset
                var resources = PHAssetResource.assetResources(for: asset)
                var orgFilename = (resources[0]).originalFilename
                print("File Name: ",orgFilename)
            }

Upvotes: 4

Mikey
Mikey

Reputation: 1332

If you have access to the user's photo library, you'll be able to actually get the PHAsset value as expected from UIImagePickerController. It seems as though UIImagePickerController will not ask for permissions on your behalf so you'll need to do this yourself.

See Determine if the access to photo library is set or not - PHPhotoLibrary for a related discussion on how you may be able to check and ask for permissions.

Upvotes: 2

crashoverride777
crashoverride777

Reputation: 10674

It seems like Apple has not added the new iOS 11 key to the info dictionary. Therefore the iOS 11 code will no work as it keeps returning nil. See this open radar http://www.openradar.me/34404703

Only solution I found so far is to use the iOS 10 code block even in iOS 11 and just ignore the UIImagePickerControllerReferenceURL deprecated message (the key still exists and works in iOS 11)

Hope this helps

Upvotes: 5

Related Questions