首页 > 解决方案 > 解释图像缓存代码的作用

问题描述

有人可以解释这个图像缓存代码是如何工作的吗?我知道正在执行一项任务来下载 imageURL 的内容,检查是否存在错误并将其显示在主线程上。但是 forKey: url.absoluteString as NSString 有什么用呢?

func downloadImage(from urlString: String ) {
        guard let url = URL(string: urlString) else { return }
        storeCache(url: url)
    }
    
    func storeCache(url:URL){
        if let cachedImage = imageCache.object(forKey: url.absoluteString as NSString) as? UIImage {
            self.image = cachedImage
        }else {
            let _: Void = URLSession.shared.dataTask(with: url) { [weak self] data, response, error in
                guard let self = self else { return }
                if error != nil { return }
                DispatchQueue.main.async {
                    if let downloadedImage = UIImage(data: data!) {
                        imageCache.setObject(downloadedImage, forKey: url.absoluteString as NSString)
                        self.image = downloadedImage
                    }
                }
            }.resume()
        }
    }
    

标签: swiftimage

解决方案


您的缓存基本上是一本精美的[url: image]字典。它允许设备请求一次,然后记住图像,直到应用程序关闭。

每次您需要图像时,您的应用程序都会检查缓存,就像字典一样,并询问是否已经从该 url 下载了图像。

if let cachedImage = imageCache.object(forKey: url.absoluteString... // empty

当然,当他们第一次运行应用程序时,缓存是空的。所以它从互联网上抓取图像并将其存储在缓存中,记住它来自哪个 url。

imageCache.setObject(downloadedImage, forKey: url.absoluteString... // cache the image

从现在开始,只要它需要来自同一个 url 的图像,它就会检查缓存并查看您是否已经下载了它。没有更多的要求。

if let cachedImage = imageCache.object(forKey: url.absoluteString... // something there!


推荐阅读