Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")
     }
like image 967
Zizoo Avatar asked Dec 05 '22 16:12

Zizoo


2 Answers

You can use this version of sd_setImage method:

cell.empPhoto.sd_setImageWithURL(url, placeholderImage:UIImage(imageNamed:"placeholder.png"))

placeholderImage will be the default image if the url does not contains a valid image.

Additional Note: you might want to check Kingfisher, it is built inspired by SDWebImage, but is it built using Swift.

like image 156
Ahmad F Avatar answered May 03 '23 17:05

Ahmad F


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

Swift

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

Objective-C

[cell.empPhoto.image sd_setImageWithURL:url placeholderImage:placeholderImage];
like image 39
ramacode Avatar answered May 03 '23 17:05

ramacode