Alamofire 无法禁用缓存

Alamofire unable disable caching

我无法让 Alamofire 或 iOS 停止缓存:

Alamofire.SessionManager.default.session.configuration.requestCachePolicy = .reloadIgnoringLocalCacheData

URLCache.shared.removeAllCachedResponses()

我需要为所有请求禁用它吗?

也尝试过:

let configuration = URLSessionConfiguration.default
configuration.urlCache = nil
let manager = Alamofire.SessionManager(configuration: configuration)

这给出了这个错误:

Auth request failed with error:
 Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo={NSErrorFailingURLKey=http://localhost:8080/slow/file.json, NSLocalizedDescription=cancelled, NSErrorFailingURLStringKey=http://localhost:8080/slow/file.json}

我在每个 Alamofire 请求停止缓存之前使用 URLCache.shared.removeAllCachedResponses()

要禁用 urlCache,您必须创建自定义 Alamofire Manager 使用 nil urlCache。

let configuration = URLSessionConfiguration.default
configuration.urlCache = nil
let manager = Manager(configuration: configuration)

您可以在 Apple Documenation

中找到更多信息

To disable caching, set this property to nil.

这是有效的:

URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)

然后 Alamofire.request

您不能更改已用于初始化 URLSessionURLSessionConfiguration 的属性,这正是您的代码示例所做的。与 一样,如果您想要此行为,您应该创建自己的禁用缓存的 Alamofire SessionManager

A​​lamofire 5.0 中,您应该创建一个 ResponseCacher 的实例并将其缓存行为设置为 .doNotCache,然后将其注入一个新的 Session 并仅使用该会话:

static let mySession = Session(cachedResponseHandler: ResponseCacher(behavior: .doNotCache))