未找到阿拉莫火缓存

问题描述 投票:0回答:1

我一直在尝试为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. 该应用从来没有从缓存中获取数据,知道为什么会出现这种情况吗?

谢谢你!

swift alamofire nsurlcache
1个回答
1
投票

这里有几个问题。

首先,目前 response.request 返回最后一个 URLRequestAlamofire 锯,这不一定是 URLRequest 的执行,并通过网络发出去。要查看该值,您实际上需要捕获Alamofire的 Request 并检查其 task?.currentRequest 财产。这应该给你 URLRequest 通过阿拉莫火和 URLSession 并进行了。我们正在研究制作这些 URLRequest的响应也是可用的。

第二,如果你只是想检查你是否收到了一个缓存的响应,最好是检查 URLSessionTaskMetrics 值,因为这应该可以提供一个明确的答案,而无需检查 URLCache.

response.metrics?.transactionMetrics.last?.resourceFetchType

如果该值为 .localCache,那么你就知道你的响应来自于缓存。

© www.soinside.com 2019 - 2024. All rights reserved.