Validate Cached HTTP Response

Using the class family URLSession, is there a way to verify the correctness of the answer? In particular, I have an HTTP response whose header Cache-Controlindicates no-cache, so any cached response must be sent for verification before using it. I can get the object CachedURLResponsefrom URLCache.shared, but none of URLSession, URLCacheor CachedURLResponse, it seems, has methods to determine if such a cached answer is saved. Such methods are also absent in URLSessionDelegateand URLSessionTaskDelegate.

Is there a way to do this differently than initiating the validation request itself? Presumably, this is being done somewhere on the stack URLSession(although I'm not sure about that), but it looks like this function may simply not be displayed by the public API.

+4
source share
2 answers

The question is why you need to verify the correctness. If you only want to verify the correctness, you can probably use an unusual method, using URLProtocoland writing a custom one NSURLProtocolClient. The client has only empty methods, except:

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

Now you are creating a protocol with this client

let myClient = ...
let protocol = NSURLProtocol(request, cachedResponse, client: myClient)

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

, HTTP . ( , , ).

URLRequest useProtocolCachePolicy. , URL, HTTP If-None-Match, Etag .

, , Etag . , If-None-Match .

TL; DR

:

  • Cache-Control Etag .

  • If-None-Match Etag .

  • ( , If-None-Match ).

:

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

+1

Source: https://habr.com/ru/post/1691642/


All Articles