Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically expire NSURLCache with max-age=0

I am using NSURLCache with AFNetworking. Caching works fine but there is no way to check if a response was actually retrieved from cache. To check if a cached version is available, I use

[[NSURLCache sharedURLCache] cachedResponseForRequest:_request];

to check for a cached version of my file.

My server is sending the following headers:

Cache-Control:public, must-revalidate, max-age=0
ETag:"317a405bf9f69346c1f0438736a3d02e"

This should basically make sure that the cached response is stale immediately after download. However, cachedResponseForRequest: still loads the previously cached version on disk, even if it actually is expired.

  • Does NSURLCache never expire or am I not sending the correct headers, etc?
  • Am I missing something else here?

EDIT

I have also tried to send

Expires: "Mon, 27 May 2013 14:34:50 GMT"

header and the response is still returned from the cache, even if it already expired. I get the feeling that NSURLCache is not working correctly...

like image 785
alex Avatar asked Nov 02 '22 21:11

alex


1 Answers

NSURLCache is used automatically by most of the iOS network APIs (such as NSURLConnection). You just need to instantiate a NSURLCache object and set it using [NSURLCache setSharedURLCache:] somewhere before making any network request.

Even if max-age=0 is set, if ETag is provided, NSURLCache has to store the response so that it can send next request with If-None-Match request header set to the previous ETag value. If server replies with 304, it returns the cached response.

So I think cachedResponseForRequest: is returning the cached response regardless of whether it's actually valid or not.

You won't need to get the cache directly. It's all managed transparently by iOS.

like image 182
Todd Avatar answered Nov 11 '22 15:11

Todd