且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何知道NSURLSessionDataTask响应是否来自缓存?

更新时间:2023-11-27 15:04:22

想到两个简单的选择:


  • 调用 [[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.