UIImageView有时无法加载

时间:2018-07-05 18:31:35

标签: swift

我有一个从使用此UIImageView扩展名的URL加载用户图片的功能:

let imageCache = NSCache<AnyObject, AnyObject>()

extension UIImageView {

    func loadImageUsingCacheWithUrlString(urlString: String) {

        self.image = nil
        print("here the URL of the image", urlString)
        //check cache for image first
        if let cachedImage = imageCache.object(forKey: urlString as AnyObject) {
            self.image = cachedImage as? UIImage
            return
        }
        // otherwise fire off a new download
        let url = URL(string: urlString)
        URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
            if error != nil {
                print(error!)
                return
            }
            DispatchQueue.main.async {
                if let downloadedImage = UIImage(data: data!) {

                    imageCache.setObject(downloadedImage, forKey: urlString as AnyObject)

                    self.image = downloadedImage
                }
            }
        }).resume()
    }
}

现在,我遇到的问题是,有时加载了个人资料图片,有时却未加载。我想发生这种情况是因为该函数异步下载了图像,但是为什么下载后它却没有出现在配置文件中? 我这样称呼它:

if hostPerfil != nil {
    if let photo = hostPerfil?.picture {
       hostPic.loadImageUsingCacheWithUrlString(urlString: photo)
    }
    hostName.text = hostPerfil!.firstName
}

我在做什么错?有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

从imageCache获取图像时,需要在主UI线程内设置UIImageView的图像,以便可以正确呈现该图像。您在下载时就做到了,这就是为什么要显示它,但是当您从缓存中获取它时也必须这样做。

DispatchQueue.main.async {
    if let cachedImage = imageCache.object(forKey: urlString as AnyObject) {
        self.image = cachedImage as? UIImage
        return
    }
}