如何知道NSURLSessionDataTask响应是否来自缓存? [英] How to know if NSURLSessionDataTask response came from cache?

查看:333
本文介绍了如何知道NSURLSessionDataTask响应是否来自缓存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想确定 NSURLSessionDataTask 的响应是来自缓存还是来自服务器

I would like to determine if the response from NSURLSessionDataTask came from cache, or was served from server

我从

request.cachePolicy = NSURLRequestUseProtocolCachePolicy;


推荐答案

想到两个简单的选择:


  • 调用 [[NSURLCache sharedURLCache] cachedResponseForRequest:request] 在发出请求之前,存储缓存响应,然后在完成接收数据后再次执行此操作,然后比较两个缓存的响应以查看它们是否相同。

  • 使用 NSURLRequestReturnCacheDataDontLoad发出初始请求缓存策略,如果失败,则使用更合理的策略发出第二个请求。

  • 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.

这篇关于如何知道NSURLSessionDataTask响应是否来自缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆