Swift 图像缓存&x2013;如何控制何时处理图像?

Swift 图像缓存&x2013;如何控制何时处理图像?,swift,caching,kingfisher,Swift,Caching,Kingfisher,我需要在磁盘上缓存图像,但要限制为20个图像。我正在尝试Nukelibrary。当我跑的时候 Nuke.loadImage(with: url, options: options, into: imageView) 只要我在视图控制器中,图像就会被缓存。当我离开视图时,下次再次获取图像时。那么,我如何使Nuke(或其他lib)保存这些图像以用于特定的图像计数或时间 在尝试Nuke之前,我只是在每次获取图像时将图像保存到应用程序的文档文件夹中。我相信有更好的办法 更新:我能用翠鸟做这件事 fun

我需要在磁盘上缓存图像,但要限制为20个图像。我正在尝试
Nuke
library。当我跑的时候

Nuke.loadImage(with: url, options: options, into: imageView)
只要我在视图控制器中,图像就会被缓存。当我离开视图时,下次再次获取图像时。那么,我如何使
Nuke
(或其他lib)保存这些图像以用于特定的图像计数或时间

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

更新:我能用翠鸟做这件事

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
从磁盘缓存中获取图像。稍后从内存缓存中删除。只有在收到内存警告时,才会释放它们。我希望是这样。上帝保佑我们。

图像缓存有几个高级选项。您可以直接访问
内存缓存
(默认Nuke的
图像管道
有两个缓存层):

另外,使用
图像预热器
类。预热(又称预取)意味着在预期使用图像之前提前加载图像
Nuke
lib提供了一个
ImagePrewarer
类,它只执行以下操作:

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
lib与
Preheat
库结合使用,该库自动预热
UICollectionView
UITableView
中的内容。在iOS 10.0及以上版本上,您可能希望使用iOS提供的新预取API。

您应该检查此库AlamofireImage库提供了相当好的图像缓存功能
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)