有人能解释一下这个图像缓存代码是如何工作的吗?我知道正在做一个任务来下载imageURL的内容,检查是否存在错误,并在主线程上显示它。但是forKey: url.absoluteString作为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()
}
}发布于 2021-02-13 15:50:11
您的缓存基本上就是一个花哨的[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!
https://stackoverflow.com/questions/66182788
复制相似问题