Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AlamoFire Ignore Cache-Control Headers

Tags:

alamofire

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.

like image 466
Steve Avatar asked Oct 01 '15 17:10

Steve


People also ask

What is a cache-control header?

The Cache-Control HTTP header holds directives (instructions) for caching in both requests and responses. A given directive in a request does not mean the same directive should be in the response. A given directive in a request does not mean the same directive should be in the response.

What does no-store do in Cache Control?

Cache-Control: no-store The no-store directive will prevent a new resource being cached, but it will not prevent the cache from responding with a non-stale resource that was cached as the result of an earlier request.

How to prevent a response from being stored in a cache?

The response may be stored by any cache, even if the response is normally non-cacheable. The response may be stored only by a browser's cache, even if the response is normally non-cacheable. If you mean to not store the response in any cache, use no-store instead. This directive is not effective in preventing caches from storing your response.

What are the HTTP headers used for caching?

The Cache-Control HTTP header holds directives (instructions) for caching in both requests and responses. A given directive in a request does not mean the same directive should be in the response. Header type. Request header, Response header. Forbidden header name.


Video Answer


1 Answers

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.

like image 197
cnoon Avatar answered Oct 12 '22 13:10

cnoon