swift - 解释图像缓存代码的作用
问题描述
有人可以解释这个图像缓存代码是如何工作的吗?我知道正在执行一项任务来下载 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()
}
}
解决方案
您的缓存基本上是一本精美的[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!
推荐阅读
- c++ - 为什么可以向外部库添加函数以访问内部数据
- javascript - Yup & React Hook Form:如何验证 onChange 而不是 onSubmit
- google-apps-script - 使用脚本在 Gmail 主题行中搜索单元格值,然后转发电子邮件
- javascript - Nodemailer:无法发送嵌入图像
- r - 在 UTM 中创建具有混合区域的唯一对象
- java - 自定义异常未运行,抛出其他异常但未自定义。我应该为自定义异常做什么?
- python - 如何访问测试脚本之外的标记列表
- nestjs - NestJS & Multer 图像类型检查错误响应客户端
- c# - UnitOfWork 的 DbSet 扩展
- dependencies - OTP 24 上的 ExCrypto