通过执行以下配置,我一直试图设置Alamofire 5.0的缓存:
private func buildURLCache() -> URLCache {
let capacity = 50 * 1024 * 1024 // MBs
#if targetEnvironment(macCatalyst)
return URLCache(memoryCapacity: capacity, diskCapacity: capacity)
#else
return URLCache(memoryCapacity: capacity, diskCapacity: capacity, diskPath: nil)
#endif
}
private func defaultSessionManager(_ requestInterceptor: RequestInterceptor?) -> Alamofire.Session {
let evaluators: [String: ServerTrustEvaluating] = [
"google.com": PinnedCertificatesTrustEvaluator(certificates: pinnedCertificates())
]
// Create custom manager
let configuration = URLSessionConfiguration.af.default
configuration.headers = HTTPHeaders.default
configuration.requestCachePolicy = .useProtocolCachePolicy
URLCache.shared = buildURLCache()
configuration.urlCache = URLCache.shared
return Alamofire.Session(
configuration: configuration,
interceptor: requestInterceptor,
serverTrustManager: ServerTrustManager(evaluators: evaluators))
}函数defaultSessionManager(_)返回一个配置好的Alamofire实例,我将其作为强引用,然后执行如下所示的请求(不要担心,这只是一个示例):
let alamofireManager = defaultSessionManager(nil)
func getFoos(
token: String,
completion: @escaping (Result<[Foo], Error>) -> Void) {
alamofireManager.request(
"google.com",
encoding: JSONEncoding.default,
headers: headers(token))
.validate()
.responseJSON { (dataResponse: AFDataResponse<Any>) in
if let cacheData = URLCache.shared.cachedResponse(for: dataResponse.request!) {
print("URLCache.shared Data is from cache")
} else {
print("URLCache.shared Data is from Server")
}
if let cacheData = URLCache.shared.cachedResponse(for: (dataResponse.request?.urlRequest!)!) {
print("URLCache.shared urlRequest Data is from cache")
} else {
print("URLCache.shared urlRequest Data is from Server")
}
//....
}
}不幸的是,函数URLCache.shared.cachedResponse正在返回nil,导致函数只打印... Data is from Server。这个应用程序永远不会从缓存中获取数据,知道为什么会发生这种情况吗?
谢谢!
发布于 2020-05-05 16:07:35
这里有几个问题。
首先,当前response.request返回Alamofire看到的最后一个URLRequest,这不一定是在网络上执行和输出的URLRequest。要查看该值,实际上需要捕获Alamofire Request并检查其task?.currentRequest属性。这将为您提供通过Alamofire和URLSession执行的URLSession。我们也在研究如何使这些URLRequest从响应中获得。
其次,如果您只想检查是否收到缓存的响应,最好检查URLSessionTaskMetrics值,因为这应该提供一个明确的答案,而不需要检查URLCache。
response.metrics?.transactionMetrics.last?.resourceFetchType如果这个值是.localCache,那么您就知道您的响应来自缓存。
https://stackoverflow.com/questions/61616846
复制相似问题