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
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.
From SDWebImage Documentation :
Using blocks
With blocks, you can be notified about the image download progress and whenever the image retrieval has completed with success or not:
// Here we use the new provided sd_setImageWithURL: method to load the web image
for Swift :
cell.imageView.sd_setImageWithURL(url, placeholderImage:nil, completed: { (image, error, cacheType, url) -> Void in
if (error) {
// set the placeholder image here
} else {
// success ... use the image
}
})
for Objective-C
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
placeholderImage:nil
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
if (error) {
self.imageView.image = [UIImage imageNamed:@"placeHolderImage"];
}
}];
You can do that by passing nil
to the placeholder attribute and handling the completion block yourself.
Like this :
[self.imageView sd_setImageWithURL:self.imageURL
placeholderImage:nil
options:nil
progress:nil
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
if(!error) {
self.imageView.image = image;
} else {
self.imageView.image = [UIImage imageNamed:@"placeHolder"];
}
}];
I haven't tried that. Try it and tell me if that worked for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With