找不到 Alamofire 缓存

Alamofire Cache not found

我一直在尝试通过以下配置为 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(_) returns 函数 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。该应用程序永远不会从缓存中获取数据,知道为什么会这样吗?

谢谢!

这里有一些问题。

首先,目前 response.request returns Alamofire 看到的最后一个 URLRequest,不一定是 URLRequest被执行并通过网络传播出去。要查看该值,您实际上需要捕获 Alamofire Request 并检查其 task?.currentRequest 属性。那应该给你 URLRequest 通过 Alamofire 和 URLSession 并被执行。我们正在考虑让这些 URLRequest 也可以从响应中获取。

其次,如果您只想检查是否收到缓存的响应,最好检查 URLSessionTaskMetrics 值,因为它应该提供明确的答案而无需检查 URLCache

response.metrics?.transactionMetrics.last?.resourceFetchType

如果此值为 .localCache,则您知道您的响应来自缓存。