如何使用带有reloadIgnoringCacheData的AlamoFire获取JSON

时间:2017-05-23 07:12:41

标签: swift alamofire

我一直试图像这样做一个简单的调用,使用自定义缓存策略从URL获取JSON数据,但我找不到简单的答案。

欢迎任何帮助。

func getScript(userID: String, success: @escaping (JSON?) -> (), failure: @escaping (NSError?) -> ()) {

    let url = CLOUDFRONT_SERVER + userID + "/" + "script.json"

    Alamofire.request(url, method: .get)
        .responseJSON { response in
            if let error = response.result.error {
                failure(error as NSError?)
            } else {
                switch response.result {
                case .success(let value):
                    success(JSON(value))
                case .failure(let error):
                    failure(error as NSError?)
                }
            }
    }
}

1 个答案:

答案 0 :(得分:0)

万一有人需要它,这是一个很好的解决方案

static let sessionManager: SessionManager = {
    let configuration = URLSessionConfiguration.default
    configuration.requestCachePolicy = .reloadIgnoringCacheData
    return SessionManager(configuration: configuration)
}()

func getScript(userID: String, success: @escaping (JSON?) -> (), failure: @escaping (NSError?) -> ()) {

    let url = CLOUDFRONT_SERVER + userID + "/" + "script.json"

    ApiManager.sessionManager.request(url, method: .get)
        .responseJSON { response in
            if let error = response.result.error {
                failure(error as NSError?)
            } else {
                switch response.result {
                case .success(let value):
                    success(JSON(value))
                case .failure(let error):
                    failure(error as NSError?)
                }
            }
    }

}