Apollo iOS swift 总是从本地缓存中获取 GraphQl

Mag*_*mel 2 cache-control ios apollo 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 }
}
Run Code Online (Sandbox Code Playgroud)

Mag*_*mel 9

来自服务器的每个查询都可以由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
}
Run Code Online (Sandbox Code Playgroud)

默认值是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)
}
Run Code Online (Sandbox Code Playgroud)