Search code examples
ioscachingnsurlsessionnsurlcache

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?


Solution

  • 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.