How to disable caching from NSURLSessionTask

Van Du Tran picture Van Du Tran · Jun 20, 2014 · Viewed 31.1k times · Source

In my iOS app, I am using NSURLSessionTask to download json data to my app. I discovered that when I call the url directly from the browser, I get an up to date json and when it's called from within the app, I get an older version of the json.

Is this due to caching? How can I tell NSURLSessionTask to not use caching.

This is the call I use:

NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

Thanks!

Answer

Dave Haupert picture Dave Haupert · Mar 10, 2017

If your read the links from @runmad you can see in the flow chart that if the HEAD of the file is unchanged it will still used the cached version when you set the cachePolicy.

In Swift3 I had to do this to get it to work:

let config = URLSessionConfiguration.default
config.requestCachePolicy = .reloadIgnoringLocalCacheData
config.urlCache = nil

let session = URLSession(configuration: config)

That got a truly non-cached version of the file, which I needed for bandwidth estimation calculations.