创建您的 URLCache 类并覆盖 storeCachedResponse 方法
class MyURLCache: URLCache {
override func storeCachedResponse(_ cachedResponse: CachedURLResponse, for request: URLRequest) {
//adding caching header if needed
var headers = response.allHeaderFields
headers.removeValue(forKey: "Cache-Control")
headers["Cache-Control"] = "max-age=\(5 * 60)" //5 min
//the trick
if (headers["isCachedReponse"] == nil){
headers["isCachedReponse"] = "true"
}
if let
headers = headers as? [String: String],
let newHTTPURLResponse = HTTPURLResponse(url: response.url!, statusCode: response.statusCode, httpVersion: "HTTP/1.1", headerFields: headers) {
let newCachedResponse = CachedURLResponse(response: newHTTPURLResponse, data: cachedResponse.data)
super.storeCachedResponse(newCachedResponse, for: request)
}
}
}
在 AppDelegate 中使用您的 URLCache 设置 URLCache.shared
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
let cache = MyURLCache(memoryCapacity: 1024 * 1024 * 500, diskCapacity: 1024 * 1024 * 500, diskPath: nil)
URLCache.shared = cache
return true
}
}
在响应回调中检查响应内容的标题是否为“newResponse”键
if (response.allHeaderFields["isCachedReponse"] == nil){
print("not cache")
} else {
print("cache")
}
适用于所有版本的 AFNetworking