How to disable caching in Alamofire

自古美人都是妖i 提交于 2019-11-26 09:34:37

问题


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.


回答1:


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)")
        }



回答2:


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.




回答3:


This is what worked for me.

NSURLCache.sharedURLCache().removeAllCachedResponses()

Swift 3

URLCache.shared.removeAllCachedResponses()



回答4:


func getImage(url: String, completion: @escaping (UIImage?) -> ()) {

    let urlRequest = URLRequest(url: URL(string: url)!)
    URLCache.shared.removeCachedResponse(for: urlRequest)
    //URLCache.shared.removeAllCachedResponses()

    Alamofire.request(url).responseData { (dataResponse) in
        guard let data = dataResponse.data else {
            return completion(nil)
        }
        completion(UIImage(data: data, scale:1))
    }
}



回答5:


In Alamofire 4 and Swift 3:

// outside function, inside class
var sessionManager: SessionManager!

func someFunc() {
    let configuration = URLSessionConfiguration.default
    configuration.urlCache = nil
    let sessionManager = Alamofire.SessionManager(configuration: configuration)
    sessionManager.request("http://example.com/get").responseJSON { response in
        // ...
    }
}



回答6:


[This approach doesn't disable caching, it merely makes sure that cached files aren't reused]

An easier way to get past cache problem for a particular call is to just add a random number in the call params.

For Swift 3, you can use, arc4random() to generate a random number.




回答7:


I solved it by doing

configuration.urlCache?.removeAllCachedResponses()



回答8:


Specifically removing a cached response before firing that request again would be more appropriate like:

let url = "http://google.com"
let urlRequest = URLRequest(url: URL(string: url)!)

URLCache.shared.removeCachedResponse(for: urlRequest)

Alamofire
  .request(urlRequest)
  .responseJSON(completionHandler: { response in
    //handle response
}


来源:https://stackoverflow.com/questions/32199494/how-to-disable-caching-in-alamofire

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!