I'm using AFNetworking 1.3.3 to fetch static JSON files from Amazon S3. If I request those files using Google Chrome and inspect the headers, it sends a If-Modified-Since and If-None-Match HTTP header in the request, and you get back a nice 304 response as expected.
However, when I make the same request using AFNetworking, sending the same If-Modified-Since and the same If-None-Match headers, I get a 200 every time, even though I know the content is not modified. It seems to be ignoring the extra headers I send.
Here's my code:
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:feedUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
if (feed.remoteLastModified != nil) {
// In real life I use the last modified header returned by the request
[request setValue:@"Tue, 10 Dec 2013 07:15:50 GMT" forHTTPHeaderField:@"If-Modified-Since"];
}
if (feed.remoteETag.length > 0) {
NSLog(@"If-None-Match: %@", feed.remoteETag);
[request setValue:feed.remoteETag forHTTPHeaderField:@"If-None-Match"];
}
NSLog(@"headers: %@", request.allHTTPHeaderFields);
AFJSONRequestOperation* operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest* request, NSHTTPURLResponse* response, id JSON) {
NSLog(@"Status code: %d", response.statusCode);
} failure:^(NSURLRequest* request, NSHTTPURLResponse* response, NSError* error, id JSON) {
if (response.statusCode != 304) {
NSLog(@"There was an error: %@", [error userInfo]);
} else {
NSLog(@"Not modified");
}
}];
[operation start];
The issue is the cache policy used - with NSURLRequestUseProtocolCachePolicy NSURLCache will be doing its own caching behind the scenes and will transparently return cached results with the original 200 response.
If you actually do want to do the caching yourself, use the NSURLRequestReloadIgnoringLocalCacheData cache policy. This doesn't mean that it will ignore YOUR cache headers (what I originally assumed) - it just means that NSURLCache will ignore it's own local cache.
However, doing this yourself and reinventing the wheel is probably the wrong way to go!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With