ios 如何在 Alamofire 中禁用缓存

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32199494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 07:23:36  来源:igfitidea点击:

How to disable caching in Alamofire

iosswiftcachingalamofire

提问by Rémi Telenczak

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.

当我使用 Alamofire 发送两次 GET 请求时,我得到相同的响应,但我期待不同的响应。我想知道是否是因为缓存,如果是,我想知道如何禁用它。

采纳答案by Andrew

swift 3, alamofire 4

迅速 3,阿拉莫火 4

My solution was:

我的解决方案是:

creating extension for Alamofire:

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

回答by cnoon

You have a few options.

你有几个选择。

Disabling the URLCache Completely

完全禁用 URLCache

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 NSURLSessionConfigurationand NSURLCache. Another great reference is NSHipster article on NSURLCache.

这两种方法都应该为您解决问题。有关更多信息,我建议通读NSURLSessionConfigurationNSURLCache的文档。另一个很好的参考是关于NSURLCache 的NSHipster 文章。

回答by Allanah Douglas

This is what worked for me.

这对我有用。

NSURLCache.sharedURLCache().removeAllCachedResponses()

Swift 3

斯威夫特 3

URLCache.shared.removeAllCachedResponses()

回答by Warif Akhand Rishi

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

回答by Rao

[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.

对于 Swift 3,您可以使用,arc4random()来生成一个随机数。

回答by u2603230

In Alamofire 4and Swift 3:

Alamofire 4Swift 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
        // ...
    }
}

回答by iAnurag

I solved it by doing

我通过做来解决它

configuration.urlCache?.removeAllCachedResponses()

回答by ardarda

Specifically removing a cached responsebefore 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
}