用于存储图像并从存储的缓存中检索的缓存不起作用-iOS Swift

时间:2019-04-08 01:10:23

标签: ios swift caching

我正在尝试下载图像并将该图像存储在缓存中。下次尝试时,从缓存中提取该图像(如果存在),否则下载该图像

我曾经浏览过类似的帖子,但没有任何帮助我解决的问题。

请咨询

    let imageCache = NSCache<NSString, UIImage>()
    func getImage(from url: URL, completion: @escaping ((UIImage?, Error?)->(Void))) {
        if let cachedImage = imageCache.object(forKey: url.absoluteString as NSString) {
            print("Image from cache")
            completion(cachedImage, nil)
        }

         NetworkOperations().downloadImage(from: url) { (data, error) in
            if let error = error {
                completion(nil, error)
            } else if let imgData = data, let image = UIImage(data: imgData) {
                self.imageCache.setObject(image, forKey: url.absoluteString as NSString)
                print("Image from cache")
                completion(image, nil)
            }

        }
    }

当我调用此方法时,它总是通过下载图像进行选择。我在这里被击中

1 个答案:

答案 0 :(得分:0)

在应用程序级别创建共享的cache并按如下所示在任意位置添加/检索/删除

class ImageCache {

    private init() {}

    static let shared = NSCache<NSString, UIImage>()
}

用法

func getImage(from url: URL, completion: @escaping ((UIImage?, Error?)->(Void))) {
        if let cachedImage = ImageCache.shared.object(forKey: url.absoluteString as NSString) {
            print("Image from cache")
            completion(cachedImage, nil)
        }

         NetworkOperations().downloadImage(from: url) { (data, error) in
            if let error = error {
                completion(nil, error)
            } else if let imgData = data, let image = UIImage(data: imgData) {
                ImageCache.shared.setObject(image, forKey: url.absoluteString as NSString)
                print("Image from cache")
                completion(image, nil)
            }

        }
    }

我希望,这可以解决问题,并且还应该使您了解实施中存在的问题。很有可能您的缓存与声明和使用它的object具有相同的作用域,因此一旦objectde-initialised,缓存也将被释放。

在以上实现中,缓存被声明为static,因此它永远不会de-initialized,但是您可以随时使用以下内容清除缓存,

ImageCache.shared.removeAllObjects()