I came cross this question when searching for a way to retrieve filename from UIImagePickerController
.
I tried all the methods mentioned in the answers, but the results were inconsistent.
As one novice iOS developer my self, I will not try to detail the mechanism between those ways. Instead I will demo my findings.
Note: all under iOS 13 with Swift 5.
The first way, which I don't think it's the really file name because it keeps changing. I guess this is the local path name because image picker saves the image to your app's temporary directory.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
guard let url = info[.imageURL] as? NSURL else { return }
let filename = url.lastPathComponent!
print(filename) // 46484E68-94E8-47B7-B0F4-E52EA7E480A9.jpeg
}
The second way, which is consitent each time I select it. I think it can be used as file name but not flawless.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let photo = info[.phAsset] as? PHAsset
var filename = photo?.value(forKey: "filename") as? String ?? ""
print(filename) // IMG_0228.JPG
}
The third way gets you the original file name, which is the file name you see in your Mac. Say you AirDrop one photo with name "Apple.jpg" to your phone, only with this way will you get the name "Apple.jpg"
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let photo = info[.phAsset] as? PHAsset
let res = PHAssetResource.assetResources(for: photo!)
let filename = res[0].originalFilename
print(filename) // Apple.jpg
}