Search code examples
iosswiftsdwebimage

Using SDWebImage for UITableViewCell with optional image URL


I am trying to the SDWebImage to populate my uitableviewcell with the image from a link from an API, the problem is the string is optional as the index in the api struct may or may not have an image. Here is the code:

        let imageString = content[index].originalImageUrl

        cell.theImageView.sd_setImage(with: URL(string: imageString!), placeholderImage: UIImage(named: "placeholder.png"))

The problem seems to be that if the originalImageURL is Nil then it crashes due to found nil as it makes me force unwrap the url. I want it to be the case that if the url is nil it uses the placeholder image instead. How can I do this?


Solution

  • Don't use force unwrap. you can use if let

      if let imageString = content[index].originalImageUrl{
        cell.theImageView.sd_setImage(with: URL(string: imageString), placeholderImage: UIImage(named: "placeholder.png"))
        }else{
        cell.theImageView.image = UIImage(named: "placeholder.png")
    }