How to know if a NSURLResponse comes from cache?
Asked Answered
P

1

19

I set NSURLCache on a specific folder (../../Application Support/Offline so it won't be deleted randomly by the OS), then I send a NSURLRequest with NSURLRequestReturnCacheDataElseLoad policy.

How can I tell that the response, handled by a class conforming to NSURLConnectionDelegate, comes from the cache or from the net?

Phillada answered 4/2, 2013 at 11:10 Comment(0)
U
8

Good article here about the problem:

http://andrewmarinov.com/ioss-corenetwork-lying/

Basically, from the NSHTTPURLResponse the status code is always 200

So if you really need to know, you can check the item is in the cache before you make the request

NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
NSHTTPURLResponse *httpCacheResponse = (NSHTTPURLResponse *)cachedResponse.response;

If so save the modified 'etag' or 'modified-date' header

NSString* etag = httpCacheResponse.allHeaderFields[@"etag"];

Then, in the response handler check the etag or modified-date is the same. If so, the response was from the cache!

Usanis answered 17/6, 2015 at 11:7 Comment(2)
that's basically what I ended up doingPhillada
you can always answer your own question! Would have saved me an hour of my life ;-)Usanis

© 2022 - 2024 — McMap. All rights reserved.