首页 > 解决方案 > Apollo iOS swift 总是从本地缓存中获取 GraphQl

问题描述

当我第一次使用 Apollo 处理每次获取的 GraphQl API 时,只有 Apollo 从服务器获取,否则总是从本地缓存获取获取

let apollo = ApolloClient(url: URL(string: graphQLEndpoint)!)
let meetingsQuery = AllMeetingsQuery()
apollo.fetch(query: meetingsQuery) { [weak self] result, error in
  guard let meetings = result?.data?.allMeetings else { return }
  print(conferences.count)
  self?.conferences = conferences.map {$0.fragments.meetingDetails }
}

标签: iosswiftgraphqlapollocache-control

解决方案


来自服务器的每个查询都可以由CachePolicy控制

一种缓存策略,指定是从服务器获取结果还是从本地缓存加载结果。

public enum CachePolicy {
  /// Return data from the cache if available, else fetch results from the server.
  case returnCacheDataElseFetch
  ///  Always fetch results from the server.
  case fetchIgnoringCacheData
  /// Return data from the cache if available, else return nil.
  case returnCacheDataDontFetch
}

默认值为returnCacheDataElseFetch,这意味着 Apollo 从缓存中返回数据(如果可用),否则从服务器获取结果。

我通过使用fetchIgnoringCacheData更改 cachePolicy 解决了这个问题

apollo.fetch(query: meetingsQuery ,cachePolicy: .fetchIgnoringCacheData)  { [weak self] result, error in
  guard let meetings = result?.data?.allMeetings else { return }
  print(conferences.count)
}

推荐阅读