I want to get the file name from UIImagePickerController
. I do not want to use ALAssetLibrary because it is deprecated in iOS 9. I have used the following code
Here is how I did it in swift 4
if let url = info[UIImagePickerController.InfoKey.imageURL] as? URL {
fileName = url.lastPathComponent
fileType = url.pathExtension
}
You can try this for iOS 11
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let asset = info[UIImagePickerControllerPHAsset] as? PHAsset {
if let fileName = (asset.value(forKey: "filename")) as? String {
//Do your stuff here
}
}
picker.dismiss(animated: true, completion: nil)
}
Make sure you add this NSPhotoLibraryUsageDescription to your Infor.plist
let fileName = (info[.imageURL] as? URL)?.lastPathComponent
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
var selectedFileName = ""
if #available(iOS 11.0, *) {
if let imageUrl = info[.imageURL] as? URL {
selectedFileName = imageUrl.lastPathComponent
}
} else {
if let imageURL = info[.referenceURL] as? URL {
let result = PHAsset.fetchAssets(withALAssetURLs: [imageURL], options: nil)
if let firstObject = result.firstObject {
let assetResources = PHAssetResource.assetResources(for: firstObject)
selectedFileName = assetResources.first?.originalFilename
}
}
}
picker.dismiss(animated: true, completion: nil)
}
Swift 5, iOS 11+
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let photo = info[.phAsset] as? PHAsset
let filename = photo?.value(forKey: "filename") as! String
}
I will suggest you to use Photos
Framework to get the name of the image, below is the code to get name of selected image
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)
}