通过swift立即使用SdWebImage和Image Change

时间:2017-07-11 04:42:35

标签: ios swift uiimageview sdwebimage

This is Question Video

使用SDWebImage我有关于imageView的问题 我更改了用户的图像,并且已经获得了新用户的图片网址,但是当我推送到此ViewController时,它将首先显示旧图像并更改为新图像。
我怎么了? 感谢。

var avatar:String = "" // previous VC data pass to here 

var photoImageView:UIImageView = { () -> UIImageView in
    let ui = GeneratorImageView()
    ui.backgroundColor = UIColor.clear
    ui.layer.masksToBounds = true 
    ui.contentMode = .scaleAspectFill
    return ui
}()

override func viewDidLoad() {
    super.viewDidLoad()

    iconImageFromUrl(imageView: iconImageView, url: avatar, isResize: false)
}    


func iconImageFromUrl(imageView:UIImageView, url:String,isResize:Bool) {

imageView.setShowActivityIndicator(true)
imageView.setIndicatorStyle(.gray)

imageView.sd_setImage(with: URL(string:url), placeholderImage: nil, options: .lowPriority, progress: nil
    , completed: { (image, error, cacheType, url) in

        guard image != nil else{
            imageView.image = resizeImage(image: #imageLiteral(resourceName: "defaultIcon"), newWidth: 50)
            return
        }

        DispatchQueue.global().async {
            let data = try? Data(contentsOf: url!) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch

            if data != nil
            {
                if let image = UIImage(data: data!)
                {
                    DispatchQueue.main.async {

                        if isResize == true{
                            imageView.image = resizeImage(image: image, newWidth: 250)
                        }else{
                            imageView.image = image
                        }
                    }
                }
            }
        }
})
}

1 个答案:

答案 0 :(得分:2)

sd_setImage方法写在UIImageView类别中。下载图像后,它会自己在UIImageview上设置图像,并在完成闭包中返回已下载/缓存的UIImage

您无需从imageUrl创建数据并重新设置。如果要调整图像大小,可以在返回的图像上执行此操作。

此外,您无需检查图像nil以设置默认图像,只需将调整后的默认图像作为占位符图像传递

imageView.sd_setImage(with: URL(string:url), placeholderImage: resizeImage(image: #imageLiteral(resourceName: "defaultIcon"), newWidth: 50), options: .lowPriority, progress: nil
, completed: { (image, error, cacheType, url) in
    guard image != nil else {
        return
    }

    if isResize {
          imageView.image = resizeImage(image: image, newWidth: 250)
    } })