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 but it always returns the image name as "Asset.jpg" for each file.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let originalImage = (info[UIImagePickerControllerOriginalImage] as? UIImage)!
let url = info[UIImagePickerControllerReferenceURL] as! NSURL
imageData = UIImageJPEGRepresentation(originalImage, 100) as NSData?
let data = UploadData()
data.fileName = url.lastPathComponent
picker.dismiss(animated: true, completion: nil)
}
This code is working for me (Swift 5):
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let imgUrl = info[UIImagePickerController.InfoKey.imageURL] as? URL{
let imgName = imgUrl.lastPathComponent
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
let localPath = documentDirectory?.appending(imgName)
let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
let data = image.pngData()! as NSData
data.write(toFile: localPath!, atomically: true)
let photoURL = URL.init(fileURLWithPath: localPath!)
let filename = photoURL.lastPathComponent
print(filename)
}
picker.dismiss(animated: true, completion: nil)
}
Before iOS 11
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let imageURL = info[UIImagePickerControllerReferenceURL] as? URL {
let result = PHAsset.fetchAssets(withALAssetURLs: [imageURL], options: nil)
let assetResources = PHAssetResource.assetResources(for: result.firstObject!)
print(assetResources.first!.originalFilename)
}
dismiss(animated: true, completion: nil)
}
After iOS 11
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let asset = info[UIImagePickerControllerPHAsset] as? PHAsset {
let assetResources = PHAssetResource.assetResources(for: asset)
print(assetResources.first!.originalFilename)
}
dismiss(animated: true, completion: nil)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With