检查缓存的HTTP响应的有效性

时间:2018-01-02 20:36:42

标签: ios swift validation caching nsurlsession

使用URLSession类系列,有没有办法检查响应的有效性?具体来说,我有一个HTTP响应,其Cache-Control标头指定no-cache,因此在使用之前必须提交任何缓存的响应以进行验证。我可以从CachedURLResponse检索URLCache.shared对象,但URLSessionURLCacheCachedURLResponse似乎没有任何方法可以确定是否存在这样的缓存响应仍然有效。 URLSessionDelegateURLSessionTaskDelegate也不存在此类方法。

除了自己启动实际验证请求之外,还有什么方法可以做到这一点吗?据推测,这是在URLSession堆栈中的某个地方完成的(虽然我对此并不确定),但看起来好像这个功能可能不会被公共API公开。

2 个答案:

答案 0 :(得分:2)

问题是为什么需要检查有效性。如果您只想检查有效性,可以使用URLProtocol并编写自定义NSURLProtocolClient来使用可能不常见的方法。客户端只有空方法,除了:

func urlProtocol(_ protocol: URLProtocol, cachedResponseIsValid cachedResponse: CachedURLResponse) {
    // Cached response is valid. Store this information in a appropriate way.
    protocol.stopLoading()
}

现在,您使用该客户端

创建协议
let myClient = ...
let protocol = NSURLProtocol(request, cachedResponse, client: myClient)

protocol.startLoading()
protocol.stopLoading() // Stop, if urlProtocol(_: cachedResponseIsValid:) was not called

答案 1 :(得分:1)

据我所知,HTTP响应的缓存是自动处理的。 (只是为了确定,我在回答这个问题之前再次尝试过)。

URLRequest上的默认缓存政策为useProtocolCachePolicy。因此,在对该网址的所有后续请求中,HTTP标头将包含If-None-Match密钥,其最新值为Etag

如果这不能自动为您服务,请确保服务器在其响应中发送Etag标头。此外,服务器确认所有请求的If-None-Match标头。

<强> TL; DR

CHECK:

  1. 您获得了Cache-ControlEtag标题 来自服务器的回复。

  2. 服务器收到If-None-Match标头 在所有后续请求中更正Etag值。

  3. 服务器实际配置为处理缓存 响应(如同,它响应If-None-Match标题 正确地)。

  4. <强>参考文献:

    https://developer.apple.com/documentation/foundation/nsurlrequest.cachepolicy https://devcenter.heroku.com/articles/ios-network-caching-http-headers