首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >找不到阿拉莫火缓存

找不到阿拉莫火缓存
EN

Stack Overflow用户
提问于 2020-05-05 15:29:46
回答 1查看 118关注 0票数 0

通过执行以下配置,我一直试图设置Alamofire 5.0的缓存:

代码语言:javascript
复制
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实例,我将其作为强引用,然后执行如下所示的请求(不要担心,这只是一个示例):

代码语言:javascript
复制
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。这个应用程序永远不会从缓存中获取数据,知道为什么会发生这种情况吗?

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-05 16:07:35

这里有几个问题。

首先,当前response.request返回Alamofire看到的最后一个URLRequest,这不一定是在网络上执行和输出的URLRequest。要查看该值,实际上需要捕获Alamofire Request并检查其task?.currentRequest属性。这将为您提供通过Alamofire和URLSession执行的URLSession。我们也在研究如何使这些URLRequest从响应中获得。

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

代码语言:javascript
复制
response.metrics?.transactionMetrics.last?.resourceFetchType

如果这个值是.localCache,那么您就知道您的响应来自缓存。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61616846

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档