How to disable the URLCache completely with Alamofire

六月ゝ 毕业季﹏ 提交于 2019-12-02 02:02:33

Why are you not configuring the session? If you configure the session correctly, there will be no caching.

Example:

//Create a non-caching configuration.
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
config.requestCachePolicy = .ReloadIgnoringLocalAndRemoteCacheData
config.URLCache = nil

//Allow cookies if needed.     
config.HTTPCookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage()


//Create a manager with the non-caching configuration that you created above.
self.manager = Alamofire.Manager(configuration: config)


//Examples of making a request using the manager you created:

//Regular HTML GET request:
self.manager.request(.GET, "https://stackoverflow.com")
    .validate(statusCode: 200..<300)
    .validate(contentType: ["text/html"])
    .responseString { (response) in
        guard response.result.isSuccess else {
            print("Error: \(response.result.error)")
            return
        }
    print("Result: \(response.result.value)")
}


//JSON GET request:
self.manager.request(.GET, "someURL", parameters: params, encoding: .URL, headers: headers)
    .validate(statusCode: 200..<300)
    .validate(contentType: ["application/json"])
    .responseJSON { (response) in
        guard response.result.isSuccess else {
            print("Error: \(response.result.error)")
            return
        }

        print(response.result.value as? [String: AnyObject])
}

Edit:

let manager = {() -> Alamofire.Manager in
    struct Static {
        static var dispatchOnceToken: dispatch_once_t = 0
        static var instance: Alamofire.Manager!
    }

    dispatch_once(&Static.dispatchOnceToken) {
        let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        config.requestCachePolicy = .ReloadIgnoringLocalAndRemoteCacheData
        config.URLCache = nil

        let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage()
        config.HTTPCookieStorage = cookies
        Static.instance = Alamofire.Manager(configuration: config)
    }

    return Static.instance
}()

manager.request(.GET, "https://stackoverflow.com")
    .validate(statusCode: 200..<300)
    .validate(contentType: ["text/html"])
    .responseString { (response) in
        guard response.result.isSuccess else {
            print("Error: \(response.result.error)")
            return
        }
    print("Result: \(response.result.value)")
}

P.S. You can also look into:

NSURLSessionConfiguration.ephemeralSessionConfiguration() - Returns a session configuration that uses no persistent storage for caches, cookies, or credentials.

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