Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get file name in UIImagePickerController with Asset library?

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)
}
like image 727
TechChain Avatar asked Nov 16 '16 09:11

TechChain


2 Answers

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)
}
like image 67
Md. Shofiulla Avatar answered Sep 23 '22 16:09

Md. Shofiulla


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)
}
like image 27
Damien D. Avatar answered Sep 23 '22 16:09

Damien D.