设置默认缓存策略 apollo swift

Ara*_*mad 4 ios swift graphql apollo-client

有没有办法快速设置Apollo框架中的默认缓存策略?

我知道我可以通过cachePolicy这种方式为每个获取请求设置缓存策略:

Apollo.shared.client.fetch(query: getUser, cachePolicy: CachePolicy.fetchIgnoringCacheData)
Run Code Online (Sandbox Code Playgroud)

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

Aam*_*irR 6

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

您可以创建一个单例 Apollo 客户端类,并使用所需的缓存策略添加您自己的 fetch 方法,如下所示

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

}
Run Code Online (Sandbox Code Playgroud)

didFinishLaunchingWithOptions可以在AppDelegate.swift 的方法中添加初始化器

let url = URL(string: "http://192.168.1.4:2223")!
ApolloManager.configure(url: url)
Run Code Online (Sandbox Code Playgroud)

您还可以使用以下命令初始化您的客户端configuration

let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = ["Authorization": "token"]
ApolloManager.configure(url: url, configuration: configuration)
Run Code Online (Sandbox Code Playgroud)

用法

ApolloManager.shared.fetch(query: getUser)
Run Code Online (Sandbox Code Playgroud)