How to disable caching from NSURLSessionTask
Swift 4 & 5
I know it's been a while, but in case it might help someone in the future.
You may also use .ephemeral
configuration property of URLSession
, which doesn't save any cookies and caches by default.
As documentation goes,
An ephemeral session configuration object is similar to a default session configuration, except that the corresponding session object doesn’t store caches, credential stores, or any session-related data to disk. Instead, session-related data is stored in RAM.
So, your code might look like this:
let configuration = URLSessionConfiguration.ephemeral
let session = URLSession(configuration: configuration)
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.
Rather than using the sharedSession
, you also can create your own NSURLSession
using a NSURLSessionConfiguration
that specifies a default cache policy. So, define a property for your session:
@property (nonatomic, strong) NSURLSession *session;
And then:
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
self.session = [NSURLSession sessionWithConfiguration:configuration];
Then requests using that session will use that requestCachePolicy
.