AlamofireImage: Can't get image in completion block from af_setImageWithURL

estemendoza picture estemendoza · Nov 26, 2015 · Viewed 8.9k times · Source

all

I am learning Swift and I am trying to set an image on a UIImageView using AlamofireImage. I am using the following code:

self.listImageView.af_setImageWithURL(
        NSURL(string: list!.image!)!,
        placeholderImage: nil,
        filter: nil,
        imageTransition: .CrossDissolve(0.5),
        completion:{ image in
            print(image)
        }
)

and the result in the console is the following:

SUCCESS: <UIImage: 0x7fb0c3ec3d30>, {512, 286}

My objective is to do something with the image once is downloaded, but the problem is that I don't understand the signature for the completion callback and I don't know how to access to the image in the completion block. According to the documentation, is Result<UIImage, NSError>.

I guess is something really simple, but I am not realizing it.

Thanks

Answer

ozgur picture ozgur · Nov 26, 2015

The image variable passed into the completion block is actually Alamofire.Response type, not the underlying UIImage instance itself that was fetched.

You need to update your completion block like below in order to get the actual image from the response:

self.listImageView.af_setImage(
    withURL: URL(string: list!.image!)!,
    placeholderImage: nil,
    filter: nil,
    imageTransition: .crossDissolve(0.5),
    completion: { response in
        print(response.value) # UIImage
        print(response.error) # NSError
    }
)

You might first want to check response.result.isSuccess (or his brother response.result.isFailure) to make sure whether the image has been successfully retrieved or not.