Prevent NSURLSession from caching responses

15,156

Solution 1

Thanks for the question. It put me on the right path.

There are more possibilities with NSURLCache.sharedURLCache() and you don't need to change the memory capacity and disk capacity for this.

You can remove all cached responses. Works for me.

URLCache.shared.removeAllCachedResponses()

Or you can remove the cache for a single response. Not working for me iOS 9.

let request = URLRequest(url: URL(string: url)!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10)
    URLCache.shared.removeCachedResponse(for: request)

//Do your request here

I hope it helps someone out!

Edit: NSURLCache.sharedURLCache().removeCachedResponseForRequest(request) is not working for me unfortunately

My alternative was: I'm using this for pull to refresh and i'm tracking the last update date. So I was using the following code:

 URLCache.shared.removeCachedResponses(since: lateUpdate)

But for some reason this is not working ether.

Since iOS 8, single cache remove methods seems to be broken: https://stackoverflow.com/a/26343653/2826164

2019-05-24, updated to Swift 5.

Solution 2

Not sure if this actually prevents from chaching or just forces a fresh reload every time, but this is what worked for me:

request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData

Here's a screenshot showing other options in case someone may need them:

enter image description here

Solution 3

I would implement URLSessionDelegate and call the completionBlock with nil in the willCache delegate implementation. This was your requests will never be chached

Share:
15,156

Related videos on Youtube

Sunkas
Author by

Sunkas

Works as developer in Gothenburg, Sweden. Specializes in native iOS and Android development.

Updated on March 21, 2020

Comments

  • Sunkas
    Sunkas about 4 years

    Why does it cache responses. It returns previously fetched responses. It even works if turning off the network connection. Resetting the iOS simulator did not seem to work either. Making a request, then again with internet offline does work (cached).

    public let urlSession: NSURLSession
    
    public init()
    {
        // ...
    
        var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
        configuration.requestCachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
        urlSession = NSURLSession(configuration: configuration)
    }
    
    func makeRequest(path: String, httpMethod:String, body:String?, baseUrl: String?, headers:[String:String]=[:], callback: JsonRequestCallback)
    {
        let urlString = (baseUrl ?? customOAuth2Manager.API_URL) + path
        let url = NSURL(string: urlString)
        let request = oauthInstance.request(forURL: url!)
    
        request.HTTPMethod = httpMethod
        self.customOAuth2Manager.setupRequest(request)
    
        for (key, value) in headers {
            request.setValue(value, forHTTPHeaderField:key)
        }
    
        if let body = body where body != "" {
            let postData = (body as NSString).dataUsingEncoding(NSUTF8StringEncoding)
            request.HTTPBody = postData
        }
    
        let task = urlSession.dataTaskWithRequest(request) { data, response, error in
            self.parseData(data, response:response, error:error, body:body, callback: callback)
        }
        task.resume()
    }
    

    Update

    I managed to solve it by calling this code from didFinishLaunching in the AppDelegate:

    func removeUrlCache()
    {
        NSURLCache.setSharedURLCache(NSURLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil))
    }
    

    However, I'm still curious why my original code does not work. It also feels a bit ugly to disable cache for all the app to solve my problem.

    • Ferran Maylinch
      Ferran Maylinch over 8 years
      Thanks!! Did you discover more about this?
    • dispatchMain
      dispatchMain almost 8 years
      add configuration.URLCache to nil when you are creating NSURLSessionConfiguration object and responses will not be cached.
  • Felipe Jun
    Felipe Jun about 8 years
    I used an alternative for removing a cached response for a specific request, reseting the cached response, see my answer in this post stackoverflow.com/a/36507745/1080583
  • Wladek Surala
    Wladek Surala over 7 years
    Do you know whether it works for simulator differently than for actual device? I used this approach, and on simulator even removing all cache on call to applicationWillResignActive still leaves full Cache.db file.
  • Gerrit Post
    Gerrit Post over 7 years
    I've tested this on device only. You can try to clean xCode cache maybe this will give a different result in de simulator (to clean xCode cache cmd+alt+shift+K)