AFNetworking 2.0 caching

So here's the deal. I recently started using AFNetworking to download multiple files on startup using the following code:

NSMutableURLRequest* rq = [api requestWithMethod:@"GET" path:@"YOUR/URL/TO/FILE"     parameters:nil];
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:rq] autorelease];

NSString* path=[@"/PATH/TO/APP" stringByAppendingPathComponent: imageNameToDisk];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

    NSLog(@"SUCCCESSFULL IMG RETRIEVE to %@!",path)

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    // Deal with failure
}];

      

My path is actually connected to a path variable (Sorry, not on the correct computer right now to actually copy pasta to text, but this is exactly the same as above with different stuff)

And everything works great! I get the file uploaded successfully and that's it. My current problem is that I am trying to get the cache to work, but I am having a lot of difficulties. Basically, I'm not sure what I actually need to do on the client side as in AFNetworking 2.0. Do I still need to configure NSURlCache? Do I need to set the cache type header differently in the request operation? I thought it might just be completely inline, but every time the code is executed I get a 200 status, even with no changes to the file. If I need to use NSUrlCache, do I need to manually store the e-tag on the request block of success blocks and then feed it back? Any help regarding progress should be much appreciated. Thanks guys!

+2


source to share


1 answer


AFNetworking uses NSURLCache for caching by default. From the FAQ :

AFNetworking uses the caching features already provided by NSURLCache

any of its subclasses. If your objects NSURLRequest

have the correct caching policy and your server's response contains a valid header Cache-Control

, the responses will be automatically cached for subsequent requests.



Note that this mechanism caches NSData

, so every time you fetch from this cache you have to perform a somewhat expensive NSData

-to- operation UIImage

. This is not enough for quick display, for example if you are displaying images in UITableView

or UICollectionView

.

If so, take a look UIImageView+AFNetworking

at what adds object loading and caching UIImage

to UIImageView

. For some applications, you can just use off-the-shelf solutions, but it's very simple. You can look at the source code for this class (it's not very long) and use it as a starting point for your own caching mechanism.

+4


source







All Articles