iosswiftphoto-galleryassetslibrary

Using assetForURL in Swift 1.2


I'm trying to get an image which is on the photo library, and I'm using assetForURL for that purpose, but I get all the time the error "Cannot invoke 'assetForURL' with an argument list of type '(NSURL, resultBlock: (ALAsset!) -> Void, (NSError!) -> Void)'"

I've checked questions here and how other people use that method, but I get always the same error.. Here is my method:

class func getImageFromPath(path: String) -> UIImage? {
    let assetsLibrary = ALAssetsLibrary()
    let url = NSURL(string: path)!

    assetsLibrary.assetForURL(url, resultBlock: { (asset: ALAsset!) -> Void in
        return UIImage(CGImage: asset.defaultRepresentation().fullResolutionImage())
    }) { (error: NSError!) -> Void in
        return nil
    }
}

I don't know what I'm missing.. thx!


Solution

  • ALAssetsLibraryAssetForURLResultBlock and ALAssetsLibraryAccessFailureBlock do not return value. (-> Void means do not have return value.)

    (ALAsset!) -> Void or (NSError!) -> Void

    So you should not return image or error inside these blocks. For example just assign local variable in block. And return the variable outside block.

    Like below:

    class func getImageFromPath(path: String) -> UIImage? {
        let assetsLibrary = ALAssetsLibrary()
        let url = NSURL(string: path)!
    
        var image: UIImage?
        var loadError: NSError?
        assetsLibrary.assetForURL(url, resultBlock: { (asset) -> Void in
            image = UIImage(CGImage: asset.defaultRepresentation().fullResolutionImage().takeUnretainedValue())
        }, failureBlock: { (error) -> Void in
            loadError = error;
        })
    
        if (!error) {
            return image
        } else {
            return nil
        }
    }