2
votes

I'm trying to get a UIImage Object from a given Asset-Library-Url. I want to make function doing this for me. The given Url is: assets-library://asset/asset.JPG?id=46811D66-DBB4-46D9-BBA2-0CF0D58FC7AD&ext=JPG I tried it with the following approach :

var url = NSURL() // url = "assets-library://asset/asset.JPG?id=46811D66-DBB4-46D9-BBA2-0CF0D58FC7AD&ext=JPG" got it from another scene
var asset = ALAssetsLibrary()
var tempImage = UIImage()
tempImage = getUIImagefromAsseturl(url)



func getUIImagefromAsseturl (url: NSURL) -> UIImage {

    asset.assetForURL(url, resultBlock: {
        (asset: ALAsset!) in
        if asset != nil {
            var assetRep: ALAssetRepresentation = asset.defaultRepresentation()
            var iref = assetRep.fullResolutionImage().takeUnretainedValue()
            var image =  UIImage(CGImage: iref)
            return image

        }
        }, failureBlock: {
            (error: NSError!) in

            NSLog("Error!", nil)
        }
    )


}

But I always get an error saying that : Cannot invoke 'assetForURL' with an argument list of type '(NSURL, resultBlock: (ALAsset!) -> _, failureBlock: (NSError!) -> _)'

Can anybody please tell me what i'm doing wrong here?

1

1 Answers

4
votes

It looks like you are trying to return your image from within the resultBlock, but that block is of type (ALAsset!) -> Void so you cannot return the image from inside the block. While Xcode's Swift error could be more clear here, I bet that because you are trying to return a UIImage from your resultBlock, the compiler has inferred the type of your provided resultBlock to be (ALAsset!) -> UIImage, which does not match the expected type of (ALAsset!) -> Void.

Because of the way assertForURL:resultBlock:failureBlock: works (both completions return type Void), you will never be able to return anything from either of the completion blocks. You will need to pass the code for displaying or otherwise handling the image into assertForURL:resultBlock:failureBlock: as part of the resultBlock.

Because of this, you will not be able to return the image from your function getUIImagefromAsseturl:, so you'll want to remove the return type UIImage.

If you do plan to display the image, it would be best to update the UI from within the main thread. This is pretty easy:

func getUIImagefromAsseturl (url: NSURL) {

    asset.assetForURL(url, resultBlock: { asset in
        if let ast = asset {
            let assetRep = ast.defaultRepresentation()
            let iref = assetRep.fullResolutionImage().takeUnretainedValue()
            let image = UIImage(CGImage: iref)
            dispatch_async(dispatch_get_main_queue(), {
                // ...Update UI with image here
            })
        }
    }, failureBlock: { error in
        println("Error: \(error)")
    })
}