Search code examples
iosswiftalassetslibrary

Can you get image file name from assetURL in IOS?


I'm saving images to photolibrary using ALAssetsLibrary and printing out the url of the image file. I noticed that photos are saved to the ios device with IMG_####.jpg format where #### is some number. I would like to get the filename of the image that I just saved. Anyway to get this IMG_####.jpg file name from the url?

assetLib.writeImage(toSavedPhotosAlbum: imageToSave.cgImage, orientation: ALAssetOrientation(rawValue: imageToSave.imageOrientation.rawValue)!, completionBlock: {(url,error) -> Void in
            print("image url: \(url)")

output

image url: Optional(assets-library://asset/asset.JPG?id=56963951-1CE3-4A1A-B693-804899C79BA5&ext=JPG)

In the comments of this link there is someone doing exactly what I want however I'm not too familiar with objective C and not using imagePickerController. If someone could explain to me how to do this in Swift without imagePickerController that would be awesome.

http://ootips.org/yonat/how-to-set-the-image-name-when-saving-to-the-camera-roll/


Solution

  • I figured it out if anyone else is interested in doing the same thing. Credits to the link I posted in question I just translated it to Swift.

        let assetLib = ALAssetsLibrary()
        //Save image get access to the url in completion handler    
        assetLib.writeImage(toSavedPhotosAlbum: imageToSave.cgImage, orientation: ALAssetOrientation(rawValue: imageToSave.imageOrientation.rawValue)!, completionBlock: {(url,error) -> Void in
                            let phAsset = PHAsset.fetchAssets(withALAssetURLs: [url!], options: nil)
                            let lastPhAsset = phAsset.lastObject
                            let asset = assetLib.asset(for: url, resultBlock: {(asset) -> Void in
                                //print("Asset Success!")
                                let imageRequestOptions = PHImageRequestOptions()
                                imageRequestOptions.isSynchronous = true
                                PHImageManager.default().requestImageData(for: lastPhAsset!, options: imageRequestOptions, resultHandler: {
                                    (data,string,orientation,diction) -> Void in
    
    
                                    let filename = diction![AnyHashable("PHImageFileURLKey")]!
                                    // You should have the correct filename here.
                                    //print("Filename = \(filename)")
                                })
    
                            }, failureBlock: {(error) -> Void in
                                print("Failed to retrieve a asset from url.")
                                return
                            })
    
    
      })