【问题标题】:Swift 4 - How To load images using cache?Swift 4 - 如何使用缓存加载图像?
【发布时间】:2018-12-23 11:23:48
【问题描述】:

我有 UIImageView,如果存在我想下载缓存中的图像,我使用了扩展 func。

我有这段代码,但不工作:

extension UIImageView {
    func loadImageUsingCache (_ urlString : String) {
        let imageCache = NSCache<AnyObject, AnyObject>()
        if let cachedImage = imageCache.object(forKey: urlString as AnyObject) {
            self.image = cachedImage as? UIImage
            return
        }
        let url = URL(string: urlString)
        URLSession.shared.dataTask(with: url!) { (data, response, error) in
            if data != nil {
                if let image = UIImage(data: data!) {
                    imageCache.setObject(image, forKey: urlString as AnyObject)
                    DispatchQueue.main.async(execute: {
                        self.image = image
                    })
                }
            }
        }.resume()
    }
}

【问题讨论】:

  • 请解释一下不起作用。你的代码没有编译?或者导致运行时错误?如果你得到错误,在哪一行和什么样的消息?或者它运行没有任何问题,但你得到了意想不到的结果?解释所有这些事情。

标签: swift image url caching uiimageview


【解决方案1】:

您正在为每个图像创建新的 NSCache 对象,而不是保留它。 您应该创建对象变量而不是本地变量。在这种情况下,它在扩展中不起作用。您也可以尝试改用 URLCache.shared。

【讨论】:

    【解决方案2】:

    // 这是完美的解决方案 //

    var imageCache = String: UIImage

    类 CustomImageView: UIImageView {

    var lastImgUrlUsedToLoadImage: String?
    
    func loadImage(with urlString: String) {
    
        // set image to nil
        self.image = nil
    
        // set lastImgUrlUsedToLoadImage
        lastImgUrlUsedToLoadImage = urlString
    
        // check if image exists in cache
        if let cachedImage = imageCache[urlString] {
            self.image = cachedImage
            return
        }
    
        // url for image location
        guard let url = URL(string: urlString) else { return }
    
        // fetch contents of URL
        URLSession.shared.dataTask(with: url) { (data, response, error) in
    
            // handle error
            if let error = error {
                print("Failed to load image with error", error.localizedDescription)
            }
    
            if self.lastImgUrlUsedToLoadImage != url.absoluteString {
                return
            }
    
            // image data
            guard let imageData = data else { return }
    
            // create image using image data
            let photoImage = UIImage(data: imageData)
    
            // set key and value for image cache
            imageCache[url.absoluteString] = photoImage
    
            // set image
            DispatchQueue.main.async {
                self.image = photoImage
            }
            }.resume()
    }
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-20
      • 1970-01-01
      • 2017-04-13
      • 2018-11-28
      • 2014-11-16
      • 1970-01-01
      • 1970-01-01
      • 2013-05-02
      相关资源
      最近更新 更多