2016-07-13 15 views
2

我有一个定制的UICollectionViewCell,它可以通过AlamofireImage(2.4)获取图像。它下载确定,但它似乎没有放入缓存。AlamofireImage Collection cell下载后将图像放入AutoPurgingImageCache中

我有一个快速的文件与我的全局缓存。

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再次加载该单元格时,它只是再次下载图像。任何想法为什么这不起作用?

+1

我修复了这个问题。我对正在下载的图像做了缓存太小,所以在我能够重新使用图像之前清除缓存。要检查缓存正在使用的内存大小,请使用** imageCache.memoryUsage **。 – skymook

回答

0

我发现我只需要使缓存的大小更大。我下载的图片比我预测的要大,而且缓存填满得太快,然后清除。

// 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)')