仅当图像无法加载 SDWebImage 时设置占位符图像

Set placeholder image only if image fails to load SDWebImage

我想在下载进行之前显示 imageview 的背景颜色,如果下载失败或图像不可用,那么我想显示一个占位符图像。我怎样才能做到这一点?

主要objective是稍后设置图片,而不是在加载时设置。

谢谢

来自 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

对于 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
            }
        })

对于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"];
                                    }
                                 }];

您可以通过将 nil 传递给占位符属性并自己处理完成块来实现。

像这样:

    [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"];
                             }
                             }];

我没试过。试一试,然后告诉我是否对你有用。

Swift3 的解决方案:

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
            }
}

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;
                                }
}];

希望你们觉得这有用。

给你,一个分离loading/error图像的扩展。 loadingImage 将是 SDWebImage 所称的 placeholderImage。加载出错时,errorImage 将是真正的占位符。

import Foundation
import SDWebImage

extension UIImageView {
    /// Separated loader and error images, short version.
    func zap_setImage(with url: URL?, loadingImage: UIImage?, errorImage: UIImage) {
        self.zap_setImage(with: url, loadingImage: loadingImage, errorImage: errorImage, completed: nil)
    }

    /// Separated loader and error images, long version.
    func zap_setImage(with url: URL?, loadingImage: UIImage?, errorImage: UIImage, completed: SDExternalCompletionBlock?) {
        self.sd_setImage(with: url, placeholderImage: loadingImage, options: []) { [weak self] (uiimage: UIImage?, error: Error?, sdimagecachetype: SDImageCacheType, usedurl: URL?) in
            //print("ISSUE1688 uiimage: \(String(describing: uiimage)), error: \(String(describing: error))")

            let setErrorImage: Bool
            switch error {
            case .none:
                // No error?
                if uiimage == nil {
                    // No error, but no image, so use error image
                    setErrorImage = true
                }
                else {
                    setErrorImage = false
                }
                break
            case .some(_):
//          case .some(let errorvalue):
                // Error?
                //print("ISSUE1688 errorvalue: \(errorvalue)")
                setErrorImage = true
                break
            }

            //print("ISSUE1688 setErrorImage: \(setErrorImage)")
            if setErrorImage {
                self?.image = errorImage
            }

            if let c = completed {
                c(uiimage, error, sdimagecachetype, usedurl)
            }
        }
    }
}

你可以用这个。

cell.img_UserProfile.sd_setImage(with: URL.init(string: "\(BaseURL_Image)\(image)"), placeholderImage: #imageLiteral(resourceName: "Group 1131"), options: .highPriority, context: [:])

与 'SDWebImage'、'~> 4.0' 使用此图像视图扩展程序

extension UIImageView {

    func setImage(imageString: String, localUri: String = "", placeHolderImage: UIImage? = nil, loader: Bool = true,  loaderType : UIActivityIndicatorView.Style = .white) {

        self.sd_setShowActivityIndicatorView(loader)
        self.sd_setIndicatorStyle(loaderType)

        if let url = URL(string: localUri), let data = try? Data(contentsOf: url), let img = UIImage(data: data) {

            self.sd_setImage(with: URL(string: imageString), placeholderImage: img, options: SDWebImageOptions(), progress: { (progress, total, url) in

            }) { (img, err, type, url) in

            }


        } else {
            self.sd_setImage(with: URL(string: imageString), placeholderImage: placeHolderImage, options: SDWebImageOptions(), progress: { (progress, total, url) in

            }) { (img, err, type, url) in

            }
        }
    }
}

从 url 加载带有占位符图像 SDWebImage 扩展名的图像 swift

extension UIImageView {
    func downloadImg(_ url: String) {
        let afterRemovedSpaceImgPath = url.replacingOccurrences(of: " ", with: "%20", options: .literal, range: nil)
        self.sd_imageIndicator = SDWebImageActivityIndicator.gray
        self.sd_setImage(with: URL(string: afterRemovedSpaceImgPath), placeholderImage: UIImage(named: "PlaceHolder"))
    }
}