skymook skymook - 8 days ago 6
Swift Question

AlamofireImage Collection cell puts image in AutoPurgingImageCache after download

I have a custom

UICollectionViewCell
that gets an image with AlamofireImage (2.4). It downloads OK, but it doesn't seem to be putting in the cache.

I have a swift file with my global cache.

import Foundation
import Alamofire
import AlamofireImage

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


The collection cell looks like this. It downloads the image with
af_setImageWithURL
and in the callback puts this image in the global cache after it sets it on the cell.

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!)
}
}
)
}
}
}


The images sets in the cell, the
print("response.result.isSuccess \(self.imageURL!)")
fires (so the call back is running), but the
print("image from cache")
never fires.
imageCache.imageWithIdentifier(imageURL!)
is always
nil
. It just downloads the image again when I load this cell again using the same URL. Any idea why this isn't working?

Answer

I found that I only needed to make the size of the cache larger. The images I was downloading were bigger than I predicted, and the cache was filling up far too quickly, then purging.

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

You can see your cache filling up if you periodically use imageCache.memoryUsage.

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