设置默认的缓存策略Apollo Swift

时间:2019-04-30 12:09:42

标签: ios swift graphql apollo-client

有什么方法可以迅速在Apollo框架中设置默认缓存策略吗?

我知道我可以通过cachePolicy参数为每个获取请求设置缓存策略,方法是:

Apollo.shared.client.fetch(query: getUser, cachePolicy: CachePolicy.fetchIgnoringCacheData)

但是我正在寻找一种在client对象中为所有请求设置缓存策略的方法。

1 个答案:

答案 0 :(得分:3)

查看源代码,没有可为ApolloClient设置的方法或cachePolicy变量。

您可以创建一个单例Apollo客户端类,并添加具有所需cachePolicy的自己的访存方法,就像这样

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)
    }

}
可以在AppDelegate.swift的didFinishLaunchingWithOptions方法中添加

Initializer

let url = URL(string: "http://192.168.1.4:2223")!
ApolloManager.configure(url: url)

您也可以使用configuration

初始化客户端
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = ["Authorization": "token"]
ApolloManager.configure(url: url, configuration: configuration)

用法

ApolloManager.shared.fetch(query: getUser)