【问题标题】:AlamofireImage Collection cell puts image in AutoPurgingImageCache after downloadAlamofireImage Collection 单元格在下载后将图像放入 AutoPurgingImageCache
【发布时间】:2016-11-16 01:54:41
【问题描述】:

我有一个自定义的UICollectionViewCell,它使用 AlamofireImage (2.4) 获取图像。它下载正常,但似乎没有放入缓存。

我的全局缓存中有一个 swift 文件。

import Foundation
import Alamofire
import AlamofireImage

// AlamofireImage cache with 30 MB cache
let imageCache = AutoPurgingImageCache(
    memoryCapacity: 30 * 1024 * 1024,
    preferredMemoryUsageAfterPurge: 20 * 1024 * 1024
)

收集单元格如下所示。它使用af_setImageWithURL 下载图像,并在回调中将此图像设置到单元格上后将其放入全局缓存中。

import UIKit
import Alamofire
import AlamofireImage

    class MyCatCell: UICollectionViewCell {

    @IBOutlet weak var fancyImage: UIImageView!

    var imageURL: String?

    func configureCell(uri: String?) {
        imageURL = uri
        resetCell()
        loadImage()
    }

    func resetCell() {
        fancyImage.af_cancelImageRequest()
        fancyImage.image = nil
    }

    func loadImage() {
        guard imageURL != nil else {
            return
        }
        if let image = imageCache.imageWithIdentifier(imageURL!) {
            // set image from cache
            print("image from cache")
            fancyImage.image = image
        } else {
            // get image and cache it
            let url = NSURL(string: imageURL!)!
            fancyImage.af_setImageWithURL(
                url,
                placeholderImage: nil,
                filter: nil,
                imageTransition: .CrossDissolve(0.5),
                completion: { response in
                    if response.result.isSuccess {
                        print("response.result.isSuccess \(self.imageURL!)")
                        // store this in the image cache
                        imageCache.addImage(response.result.value!, withIdentifier: self.imageURL!)
                    }
                }
            )
        }
    }
}

在单元格中设置图像,print("response.result.isSuccess \(self.imageURL!)") 触发(因此回调正在运行),但print("image from cache") 永远不会触发。 imageCache.imageWithIdentifier(imageURL!) 始终是 nil。当我使用相同的 URL 再次加载此单元格时,它只是再次下载图像。知道为什么这不起作用吗?

【问题讨论】:

  • 我解决了这个问题。对于正在下载的图像,我将缓存设置得太小,因此在我可以重用图像之前就清除了缓存。要检查缓存正在使用的内存大小,请使用 imageCache.memoryUsage

标签: swift uicollectionviewcell alamofireimage


【解决方案1】:

我发现我只需要使缓存的大小更大。我正在下载的图像比我预期的要大,而且缓存填得太快,然后被清除。

// AlamofireImage cache with 60 MB cache
let imageCache = AutoPurgingImageCache(
    memoryCapacity: 60 * 1024 * 1024,
    preferredMemoryUsageAfterPurge: 20 * 1024 * 1024
)

如果您定期使用 imageCache.memoryUsage,您会看到缓存已满。

Print('Image cache size = \(imageCache.memoryUsage)')

【讨论】:

    猜你喜欢
    • 2011-03-14
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    • 2016-03-02
    • 2016-02-02
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    相关资源
    最近更新 更多