Set placeholder image only if image fails to load SDWebImage

Ankit Kumar Gupta picture Ankit Kumar Gupta · Feb 2, 2017 · Viewed 14.8k times · Source

I want to show the imageview's background color till the download is in progress and if the download fails or image is not available then i want to show a placeholder image. How can i achieve this?

The main objective is to set the image later not during loading.

Thanks

Answer

Ankit Kumar Gupta picture Ankit Kumar Gupta · Feb 2, 2017

Solution for Swift 3 :

cell.imageView?.sd_setImage(with: url) { (image, error, cache, urls) in
            if (error != nil) {
                cell.imageView.image = UIImage(named: "ico_placeholder")
            } else {
                cell.imageView.image = image
            }
}

Solution for Objective C :

[cell.imageView sd_setImageWithURL:url
                  placeholderImage:nil
                         completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                                if (error) {
                                  self.imageView.image = [UIImage imageNamed:@"ico_placeholder"];
                                } else {
                                  self.imageView.image = image;
                                }
}];

Hope you guys find this useful.