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

1

10

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

Randalrandall answered 26/11, 2015 at 20:14 Comment(0)
C
31

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.

Culberson answered 26/11, 2015 at 20:44 Comment(2)
Thanks, exactly what I needed, but I have to say that the response it's not very friendly to figure that out :)Randalrandall
great . This helped me very much in my chat application.Guru

© 2022 - 2024 — McMap. All rights reserved.