有没有办法在swift中设置Apollo框架的默认缓存策略?
我知道我可以通过 cachePolicy
参数以这种方式为每个获取请求设置缓存策略:
Apollo.shared.client.fetch(query: getUser, cachePolicy: CachePolicy.fetchIgnoringCacheData)
但我正在寻找一种方法来为所有请求在 client
对象中设置缓存策略。
最佳答案
查看源代码,没有可以为 ApolloClient 设置的方法或 cachePolicy
变量。
你可以创建一个单例的 Apollo 客户端类,并添加你自己的具有所需缓存策略的获取方法,就像这样
class ApolloManager {
static let shared = Apollo()
private var client: ApolloClient!
var store: ApolloStore { return self.client.store }
static func configure(url: URL, configuration: URLSessionConfiguration? = nil) {
let store = ApolloStore(cache: InMemoryNormalizedCache())
Apollo.shared.client = ApolloClient(networkTransport: HTTPNetworkTransport(url: url, configuration: configuration ?? .default), store: store)
}
@discardableResult
func fetch<Query: GraphQLQuery>(query: Query, cachePolicy: CachePolicy = .fetchIgnoringCacheData, queue: DispatchQueue = .main, resultHandler: OperationResultHandler<Query>? = nil) -> Cancellable? {
return self.client.fetch(query: query, cachePolicy: cachePolicy, queue: queue, resultHandler: resultHandler)
}
}
Initializer可以在AppDelegate.swift的didFinishLaunchingWithOptions
方法中添加
let url = URL(string: "http://192.168.1.4:2223")!
ApolloManager.configure(url: url)
您还可以使用配置
初始化您的客户端
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = ["Authorization": "token"]
ApolloManager.configure(url: url, configuration: configuration)
用法
ApolloManager.shared.fetch(query: getUser)
关于ios - 设置默认缓存策略 apollo swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55920675/