Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pre-cache Images for AFNetworking's UIImageView category

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

like image 217
djibouti33 Avatar asked Jun 28 '12 00:06

djibouti33


2 Answers

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).

like image 87
mattt Avatar answered Oct 07 '22 01:10

mattt


I would NOT create a bunch of UIImageView's to achieve your purpose, that would be a really inefficient approach.

You could add your own method to UIImageView+AFNetworking.h to achieve this ability. I thin this would be the best approach. An untested example would be:

+ (void) cacheImageWithURL:(NSURL *)url 
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
    [request setHTTPShouldHandleCookies:NO];
    [request setHTTPShouldUsePipelining:YES];

    AFImageRequestOperation *requestOperation = [[[AFImageRequestOperation alloc] initWithRequest:request] autorelease];
    [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        [[[self class] af_sharedImageCache] cacheImage:responseObject forRequest:request];
    } 
    failure:^(AFHTTPRequestOperation *operation, NSError *error) {}];
}
like image 5
Michael Frederick Avatar answered Oct 07 '22 03:10

Michael Frederick