Search code examples
alamofire

AlamoFire Ignore Cache-Control Headers


Is it possible to ignore cache-control headers when performing a request/handling the response with AlamoFire?

Currently I am making a request as follows, and the server is returning large cache-control headers, when in fact we need to ignore them.

Alamofire.request(.GET, url).responseJSON { (_, _, result) in // Do something

I know the correct solution is to modify the server response, but this is not feasible at this time.

Also, there are other requests where I do want to honor the cache-control headers, so ideally I would a solution that does not involve changing a global configuration of AlamoFire.


Solution

  • To ignore the cached data, you need to set the cachePolicy on the NSURLRequest before using Alamofire to start it.

    let URL = NSURL(string: "https://my_url_path...")!
    let URLRequest = NSMutableURLRequest(URL: URL)
    URLRequest.cachePolicy = .ReloadIgnoringCacheData
    
    Alamofire.request(URLRequest)
        .response { response in
            print(response)
        }
    

    Setting the cachePolicy on the URL request always overrides the value set on the NSURLSessionConfiguration.

    By default, the NSURLSessionConfiguration cache policy is set to .UseProtocolCachePolicy which will honor the Cache-Control header values.