11

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)!

User558
  • 1,165
  • 1
  • 13
  • 37

3 Answers3

5

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

crashoverride777
  • 10,581
  • 2
  • 32
  • 56
  • If you have access to read photos from the library (see `PHPhotoLibrary`), the value for this key should be non-null. – Mikey May 23 '18 at 15:42
  • it is coming nil because you are not getting permission so first, you need to check PHPhotoLibrary.authorizationStatus(), if app has permission, it will return value. – Hindu Jun 27 '18 at 07:27
4

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)
            }
Mobi
  • 69
  • 8
2

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.

Mikey
  • 1,312
  • 10
  • 11