问题
I would like to determine if the response from NSURLSessionDataTask
came from cache, or was served from server
I'am creating my NSURLSessionDataTask
from
request.cachePolicy = NSURLRequestUseProtocolCachePolicy;
回答1:
Two easy options come to mind:
- Call
[[NSURLCache sharedURLCache] cachedResponseForRequest:request]
before you make the request, store the cached response, then do that again after you finish receiving data, and compare the two cached responses to see if they are the same. - Make an initial request with the
NSURLRequestReturnCacheDataDontLoad
cache policy, and if that fails, make a second request with a more sane policy.
The first approach is usually preferable, as the second approach will return data that exists in the cache even if it is stale. However, in some rare cases (e.g. an offline mode), that might be what you want, which is why I mentioned it.
回答2:
If your information need is only out of curiosity you can view your network usage the Xcode runtime network metics. Change the policy to a different setting and observe the difference.
回答3:
If you want to use caching then it's not a good answer to disable caching on the client.
if the server has set cache headers (etag, cache-control="no-store") then NSURLSession will revalidate and serve you cached / fresh response based on the 200 / 304 response from the server. However in your code you will always see statusCode 200 regardless of if NSUrlSession received 200 or 304. This is limiting, because you may want to skip parsing, re-creating objects etc when the response hasnt changed.
THe workaround I did, is to use the etag value in the response to determine if something has changed
NSHTTPURLResponse *httpResp = (NSHTTPURLResponse *)response;
NSString *etag = (httpResp && [httpResp isKindOfClass:[NSHTTPURLResponse class]]) ? httpResp.allHeaderFields[@"Etag"] : nil;
BOOL somethingHasChanged = [etag isEqualToString:oldEtag];
来源:https://stackoverflow.com/questions/40976132/how-to-know-if-nsurlsessiondatatask-response-came-from-cache