Prevent Nsurlsession from Caching Responses

Prevent caching in NSURLSession for iOS Simulator

I had a similar issue and I was able to fix this by setting the properties- URLCache and requestCachePolicy on NSURLSessionConfiguration to nil and NSURLRequestReloadIgnoringCacheData respectively.

Also, you can try setting the cachePolicy property on NSMutableURLRequest to NSURLRequestReloadIgnoringCacheData.

How to disable caching from NSURLSessionTask

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.

NSURLSession not using cached responses

I can't tell you with absolute certainty why the cache isn't being consulted, but I can give you a list of the most likely reasons:

  • The server did not respond with 304 when queried about the validity of that ETag header (IIRC using a HEAD request).
  • The request is too big—either relative to the size of the buffer or in absolute terms. The cache should at least be a couple of orders of magnitude bigger than the requests that you would typically cache; anything over about 5% of the cache size will not be cached.
  • The request method is something other than GET. (Only GET requests are cached unless you monkey with the machinery significantly.)
  • More than 10 minutes have elapsed (600 seconds isn't very long).
  • The request was made in a different URL session that has a different backing cache.
  • The request was made in an ephemeral URL session or a session that for some other reason has no cache.
  • The session actually is returning the cached response, but you're seeing a request because it is revalidating a little more aggressively than you might expect—possibly because it will reach its maximum age so soon.
  • Your URL request is getting handled in the background by a custom NSURLProtocol that doesn't respect the cache (e.g. because of some badly behaved third-party networking or advertising framework).
  • The request had not actually been fully written to the cache when you tried to retrieve it (timing race caused by multiple threads).

I'm probably forgetting several others. With that said, if I'm forgetting them, that probably means that they aren't documented.

So...

If you verify that everything listed above is working as expected, file a bug at bugreporter.apple.com and include enough code to reproduce the problem, along with a packet dump if possible.

Stop NSURLRequest writing to cache

NSURLRequest's cache policy only controls if and how the cache will be read, not whether downloaded data will be written.

If you're using NSURLRequest with NSURLSession, implement the
URLSession(_:dataTask:willCacheResponse:completionHandler:)
method in your delegate, and call the completionHandler with a nil argument.

A similar delegate call works if you're using NSURLConnection; see this question for details.

How to cache NSUrlSession response data

You can handle cache data using NSMutableURLRequest class setCachePolicy method. There are many methods works accordingly have a look.

NSURLRequestReloadIgnoringCacheData: This methods ignores cache data and fetch the fresh updated response from server.

Specifies that the data for the URL load should be loaded from the originating source. No existing cache data should be used to satisfy a URL load request.

NSURLRequestUseProtocolCachePolicy: Specifies that the caching logic defined in the protocol implementation, if any, is used for a particular URL load request. This is the default policy for URL load requests.

NSURLRequestReloadIgnoringLocalAndRemoteCacheData: Specifies that not only should the local cache data be ignored, but that proxies and other intermediates should be instructed to disregard their caches so far as the protocol allows.

Some more check here: source.

Uses:

NSURLRequest *Request = [NSURLRequest requestWithURL:[NSURL URLWithString:URLForService_Providers] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0];

OR

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setCachePolicy:NSURLRequestReloadIgnoringCacheData];

Is it possible to prevent an NSURLRequest from caching data or remove cached data following a request?

Usually it's easier to create the request like this

NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:60.0];

Then create the connection

NSURLConnection *conn = [NSURLConnection connectionWithRequest:request
delegate:self];

and implement the connection:willCacheResponse: method on the delegate. Just returning nil should do it.

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {
return nil;
}

NSURLSession and image cache

NSURLSession uses shared NSURLCache to cache responses. If you want to limit disk/memory usage of a shared cache you should create a new cache and set it as a default one:

let URLCache = NSURLCache(memoryCapacity: 4 * 1024 * 1024, diskCapacity: 20 * 1024 * 1024, diskPath: nil)
NSURLCache.setSharedURLCache(URLCache)

You could find a little more about caching here.



Related Topics



Leave a reply



Submit