【发布时间】: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