How do I invalidate iOS's cache for a particular URL?

后端 未结 3 1835
[愿得一人]
[愿得一人] 2021-01-03 00:54

Using NSURLSession\'s default caching, how do I invalidate the cache for a particular URL?

I note NSURLCache\'s removeCachedResponseF

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-03 01:31

    If you want to go further you could reset the cached response for the url request you want to force the reload. Doing the following:

    let newResponse = NSHTTPURLResponse(URL: urlrequest.URL!, statusCode: 200, HTTPVersion: "1.1", headerFields: ["Cache-Control":"max-age=0"])
    let cachedResponse = NSCachedURLResponse(response: newResponse!, data: NSData())
    NSURLCache.sharedURLCache().storeCachedResponse(cachedResponse, forRequest: urlrequest)
    

    As the cache-control header of the response hax a max age of 0 (forced) the response will never be returned when you do this request.

    Your answer works fine for forcing a single request, but if you want to have two versions of the request one forcing and another relying on the cached response, removing the cached one once you force a request is desired.

提交回复
热议问题