我有一个显示图像的集合视图,其中一些被缓存并正确检索,而另一些则没有。集合视图每行显示两个方形单元格。
我不明白为什么有时图像是从缓存中获取的,而其他时候必须再次下载。
在这里我缓存图像:
class DataImage {
static let sharedManager = DataImage()
let decoder = ImageDecoder()
let photoCache = AutoPurgingImageCache(
memoryCapacity: 100 * 1024 * 1024,
preferredMemoryUsageAfterPurge: 60 * 1024 * 1024
)
//MARK: - Image Downloading
func getNetworkImage(urlString: String, completion: (UIImage -> Void)) -> (ImageRequest) {
let queue = decoder.queue.underlyingQueue
let request = Alamofire.request(.GET, urlString)
let imageRequest = ImageRequest(request: request)
imageRequest.request.response(
queue: queue,
responseSerializer: Request.imageResponseSerializer(),
completionHandler: { response in
guard let image = response.result.value else {
return
}
let decodeOperation = self.decodeImage(image) { image in
completion(image)
self.cacheImage(image, urlString: urlString)
}
imageRequest.decodeOperation = decodeOperation
}
)
return imageRequest
}
func decodeImage(image: UIImage, completion: (UIImage -> Void)) -> DecodeOperation {
let decodeOperation = DecodeOperation(image: image, decoder: self.decoder, completion: completion)
self.decoder.queue.addOperation(decodeOperation)
return decodeOperation
}
//MARK: - Image Caching
func cacheImage(image: Image, urlString: String) {
photoCache.addImage(image, withIdentifier: urlString)
}
func cachedImage(urlString: String) -> Image? {
print("image: \(photoCache.imageWithIdentifier(urlString))")
return photoCache.imageWithIdentifier(urlString)
}
}
这是 Cell 类:
class StoreCell: UICollectionViewCell {
@IBOutlet weak var title: UILabel!
@IBOutlet weak var storyImage: UIImageView!
@IBOutlet weak var subTitle: UILabel!
@IBOutlet weak var cost: UILabel!
var imageFilename: String!
var request: ImageRequest!
var dataImage = DataImage()
func configure() {
self.layer.cornerRadius = 3.0
reset()
loadImage()
}
func reset() {
storyImage.image = nil
request?.cancel()
}
func loadImage() {
let stringURL = "https://........\(imageFilename)"
if self.storyImage.image == nil {
if let image = dataImage.cachedImage(stringURL) {
self.storyImage.image = image
} else {
request = dataImage.getNetworkImage(stringURL) { image in
self.storyImage.image = image
self.storyImage.runImageTransition(.CrossDissolve(0.2), withImage: image)
}
}
}
}
}