How to know if NSURLSessionDataTask response came from cache?

瘦欲@ 提交于 2020-01-01 09:22:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!