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

喜欢而已 提交于 2019-12-06 19:49:01

问题


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


回答1:


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




回答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.




回答3:


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


来源:https://stackoverflow.com/questions/46951683/how-to-get-image-name-from-uiimagepickercontrollerphasset-taken-with-library-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!