Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable caching in Alamofire

When I send a GET request twice with Alamofire I get the same response but I'm expecting a different one. I was wondering if it was because of the cache, and if so I'd like to know how to disable it.

like image 805
Rémi Telenczak Avatar asked Aug 25 '15 08:08

Rémi Telenczak


3 Answers

You have a few options.

Disabling the URLCache Completely

let manager: Manager = {
    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    configuration.URLCache = nil
    return Manager(configuration: configuration)
}()

Configuring the Request Cache Policy

let manager: Manager = {
    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    configuration.requestCachePolicy = .ReloadIgnoringLocalCacheData
    return Manager(configuration: configuration)
}()

Both approaches should do the trick for you. For more information, I'd suggest reading through the documentation for NSURLSessionConfiguration and NSURLCache. Another great reference is NSHipster article on NSURLCache.

like image 70
cnoon Avatar answered Nov 16 '22 11:11

cnoon


This is what worked for me.

NSURLCache.sharedURLCache().removeAllCachedResponses()

Swift 3

URLCache.shared.removeAllCachedResponses()
like image 47
Allanah Fowler Avatar answered Nov 16 '22 10:11

Allanah Fowler


swift 3, alamofire 4

My solution was:

creating extension for Alamofire:

extension Alamofire.SessionManager{
    @discardableResult
    open func requestWithoutCache(
        _ url: URLConvertible,
        method: HTTPMethod = .get,
        parameters: Parameters? = nil,
        encoding: ParameterEncoding = URLEncoding.default,
        headers: HTTPHeaders? = nil)// also you can add URLRequest.CachePolicy here as parameter
        -> DataRequest
    {
        do {
            var urlRequest = try URLRequest(url: url, method: method, headers: headers)
            urlRequest.cachePolicy = .reloadIgnoringCacheData // <<== Cache disabled
            let encodedURLRequest = try encoding.encode(urlRequest, with: parameters)
            return request(encodedURLRequest)
        } catch {
            // TODO: find a better way to handle error
            print(error)
            return request(URLRequest(url: URL(string: "http://example.com/wrong_request")!))
        }
    }
}

and using it:

Alamofire.SessionManager.default
            .requestWithoutCache("https://google.com/").response { response in
                print("Request: \(response.request)")
                print("Response: \(response.response)")
                print("Error: \(response.error)")
        }
like image 34
Andrew Avatar answered Nov 16 '22 11:11

Andrew