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

喜欢而已 提交于 2019-11-30 20:29:17

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.

The solution turns out not to be invalidating the cache for an existing URL, but to set:

request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;

When you make the next request for the resource you know to be invalid. There are options to ignore the local cache only, or to request that upstream proxies ignore their caches too. See the NSURLRequest/NSMutableURLRequest documentation for details.

Here's what has been working for me:

request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData

Here are all the options listed regarding chache policy, so you may find one that better suits your need:

Using Swift 2.2 and Xcode 7.3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!