Pre-cache Images for AFNetworking's UIImageView category

djibouti33 picture djibouti33 · Jun 28, 2012 · Viewed 7.3k times · Source

When my app loads, I pull down a JSON representation of 99 objects.

Each object has an 'image_url' field, which I pass to AFNetworking's setImageWithURLRequest.

My images load in a tableView, and consequently, only the first several cells make requests for their images. It's not until I scroll down that subsequent image requests are made.

Once I pull down the initial dataset, I'd like to be able to kick off a background process that goes out and downloads the 95 or so objects that aren't initially visible, and cache them in such a way that when setImageWithURLRequest is called, it'll already have a cached image to pull from.

AFImageCache is private though, so I'm not sure if this is possible. I know I could cache with NSURLCache, but then I'd have two separate, isolated caches, and that's not ideal either.

Is my only option to not use AFNetworking's UIImageView category?

These answers make me think so:

iOS Caching images with AFImageCache doesn't seem to work
How to configure the cache when using AFNetworking's setImageWithURL

Answer

mattt picture mattt · Jul 3, 2012

Please, please don't do this.

Trust me when I say that this almost certainly unnecessary.

In fact, it will likely have the opposite of the desired effect, due to the increased pressure of downloading images that will probably never be viewed.

The cache is private for a very good reason--it's just there to speed up subsequent requests on scroll views. Just have the table view download the images as requested, and you should be just fine. If anything, you can optimize the size of the images that you are downloading (ensure correct image dimensions; compress intelligently).