【问题标题】:cache image url not existing on rebuilding the project重建项目时缓存图像 url 不存在
【发布时间】:2019-08-01 11:24:29
【问题描述】:

我正在 ios 中实现图像缓存。 以下是我的功能。

struct DownloadImage {

static let cache = NSCache<NSString,UIImage>()

static func downloadImage(with url: URL,completion: @escaping (_ image: UIImage?) -> ()) {
    let dataTask = URLSession.shared.dataTask(with: url) { (data, responseURL, error) in
        var downloadedImage: UIImage?

        if let data = data {
            downloadedImage = UIImage(data: data)
        }
        if downloadedImage != nil {
            cache.setObject(downloadedImage!, forKey: url.absoluteString as NSString)
        }
        DispatchQueue.main.async {
            completion(downloadedImage)
        }
    }
    dataTask.resume()
}


static func getImage(withURL url:URL,completion: @escaping (_ image: UIImage?) -> ()) {
    if let image = cache.object(forKey: url.absoluteString as NSString) {
        completion(image)
    } else {
        downloadImage(with: url, completion: completion)
    }
}  

}

图像被缓存了,但是当我再次重建项目时,即使在同一个 URL 上也会调用下载图像函数?

谁能告诉我我缺少什么或为什么调用下载图像功能?

【问题讨论】:

  • NSCache 是一个内存中缓存。缓存内容不会在应用程序重新启动后保留。
  • NSCache 对象正在使用存储图像,但是您重建项目或杀死应用程序并重新启动然后cache 是新的初始化。但是你想要的代码。
  • SDWebImage 提供磁盘缓存
  • 我想要的是,如果我再次重新启动应用程序,我应该能够在没有互联网的情况下从缓存中获取图像。

标签: ios swift caching nscache


【解决方案1】:

正如其他人所提到的,您需要的是持久内存。

你可以做的保存它们是:

let fileCoordinator = NSFileCoordinator()
fileCoordinator.coordinate(writingItemAt: someURL, options: .forReplacing, error: nil, byAccessor: { _ in
     do {
          try UIImagePNGRepresentation(image)?.write(to: someURL)
     } catch let error as NSError {
          print (error)
     }
})

然后阅读它:

if let data = Data(contentsOf: someURL), let image = UIImage(data: data!) }
    return image
} else {
    print ("something wrong reading the image"
}

【讨论】:

    【解决方案2】:

    NSCache 只是一个花哨的NSDictionary。它不应该在会话中持续存在,并且即使在会话期间也不能保证将对象保留在内存中。

    因此,在您的具体情况下,每次重建应用时都会重新创建缓存。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-14
      • 1970-01-01
      • 2014-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-12
      相关资源
      最近更新 更多