diegomen
diegomen

Reputation: 1864

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!

Upvotes: 1

Views: 2717

Answers (2)

diegomen
diegomen

Reputation: 1864

Kishikawa katsumi, you were right! the problem was the return, I change my method like that and it works perfect:

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

thx!!

Upvotes: 0

kishikawa katsumi
kishikawa katsumi

Reputation: 10593

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
    }
}

Upvotes: 3

Related Questions