Zizoo Zizoo - 1 month ago 49
iOS Question

How to set default image when imageURL is empty using SDWebImage - Swift

I have the following code at

cellForRowAt
function:

let url = URL(string: myurl!)
cell.empPhoto.image? = (cell.empPhoto.image?.circle)!
cell.empPhoto.image? = (cell.empPhoto.image?.rounded)!

cell.empPhoto.sd_setImage(with: url)


I'm using
sd_setImage
from SDWebImage to download the image from url and cache it , but sometime the url is not found or has empty content, so how to give a default image for the cell if the url is empty , should I check the content of the url before using
sd_setImage
or I can just do it from the same library ?

what I want is something like this :

if url.hasImage {
cell.empPhoto.sd_setImage(with: url)
}
else{ // use default image
cell.empPhoto.image=UIImage(named: "contact")
}

Answer

It is better to have placeholder image so there will still be an image even when your request is failed.

You can set the placeholder using SDWebImage function sd_setImageWithURL:placeholderImage:options:completed

Swift

cell.empPhoto.sd_setImage(with: url, placeholderImage: placeholderImage);

Objective-C

[cell.empPhoto.image sd_setImageWithURL:url placeholderImage:placeholderImage];
Comments