【问题标题】:Image Caching – How to control when images are disposed?图像缓存——如何控制图像何时被处理?
【发布时间】:2018-10-26 03:18:59
【问题描述】:

我需要在磁盘上缓存图像,但将它们限制为 20 个图像。我正在尝试Nuke 库。当我跑步时

Nuke.loadImage(with: url, options: options, into: imageView)

只要我在我的视图控制器中,图像就会被缓存。当我离开视图时,下一次将再次获取图像。那么我如何让Nuke(或其他库)保存这些图像以用于特定的图像计数或时间。

在尝试 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 从磁盘缓存中获取图像。后来从内存缓存。只有在收到内存警告时才会释放它们。我希望确实如此。上帝帮助我们。

【问题讨论】:

标签: swift caching kingfisher


【解决方案1】:

图像缓存有几个高级选项。你可以直接访问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。

【讨论】:

    猜你喜欢
    • 2013-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-25
    • 2010-11-06
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多