图像缓存 - 如何控制何时处理图像?

时间:2018-05-16 07:19:12

标签: swift caching kingfisher

我需要在磁盘上缓存图像,但限制它们说20张图像。我正在尝试Nuke库。我跑的时候

Nuke.loadImage(with: url, options: options, into: imageView)
只要我在View Controller中,就会缓存

图像。当我离开视图时,下次再次获取图像。那么如何使Nuke(或其他lib)保存这些图像以用于特定的图像计数或时间。

在尝试Nuke之前,我每次获取图片时都只是将图像保存到应用的Documents文件夹中。我相信有更好的方法。

更新:我能够使用Kingfisher

func getFromCache(id: String) {
    ImageCache.default.retrieveImage(forKey: id, options: nil) {
        image, cacheType in

        if let image = image {
            self.galleryImageView.image = image  
        } else {
            print("Not exist in cache.")
            self.loadImage()
        }
    }
}

private func loadImage() {            
    ImageDownloader.default.downloadImage(with: url, options: [], progressBlock: nil) {
        (image, error, url, data) in

        if let image = image {
            self.galleryImageView.image = image
            ImageCache.default.store(image, forKey: id, toDisk: true)
        }
    }
}

如果我理解正确,首先retrieveImage从磁盘缓存中提取图像。后来从内存缓存。只有在收到记忆警告时它才会释放它们。我希望如此。上帝帮助我们。

1 个答案:

答案 0 :(得分:0)

有几种用于图像缓存的高级选项。您可以直接访问Memory Cache(默认的Nuke的ImagePipeline具有两个缓存层):

// Configure cache
ImageCache.shared.costLimit = 1024 * 1024 * 100 // Size in MB
ImageCache.shared.countLimit = 20 // You may use this option for your needs 
ImageCache.shared.ttl = 90 // Invalidate image after 90 sec

// Read and write images
let request = ImageRequest(url: url)
ImageCache.shared[request] = image
let image = ImageCache.shared[request]

// Clear cache
ImageCache.shared.removeAll()

此外,使用ImagePreheater类。预热(也称为预取)是指在预期使用之前提前加载图像。 Nuke lib提供了一个ImagePreheater类,该类可以做到这一点:

let preheater = ImagePreheater(pipeline: ImagePipeline.shared)

let requests = urls.map {
    var request = ImageRequest(url: $0)
    request.priority = .low
    return request
}

// User enters the screen:
preheater.startPreheating(for: requests)

// User leaves the screen:
preheater.stopPreheating(for: requests)

您可以结合使用Nuke库和Preheat库,该库可以自动预热UICollectionViewUITableView中的内容。在iOS 10.0及更高版本上,您可能想使用iOS提供的新的预取API。