Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

I note NSURLCache's removeCachedResponseForRequest: method, but that takes an NSURLRequest object, which I don't have for the original request. Do I need to store those as I create them so I can then pass them back into removeCachedResponseForRequest: or can I just create a new one with the appropriate URL which will then serve as equivalent for the purpose, even if it doesn't have the same header fields and other properties as the original?

like image 706
Robert Atkins Avatar asked Jun 30 '14 14:06

Robert Atkins


Video Answer


3 Answers

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.

like image 79
Felipe Jun Avatar answered Oct 11 '22 05:10

Felipe Jun


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.

like image 4
Robert Atkins Avatar answered Oct 11 '22 05:10

Robert Atkins


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:

enter image description here

Using Swift 2.2 and Xcode 7.3

like image 1
Andrej Avatar answered Oct 11 '22 06:10

Andrej