【问题标题】:Set default cache policy apollo swift设置默认缓存策略 apollo swift
【发布时间】:2019-09-19 02:24:10
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: ios swift graphql apollo-client


    【解决方案1】:

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

    您可以创建一个单例 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)
        }
    
    }
    

    Initializer可以添加到AppDelegate.swift的didFinishLaunchingWithOptions方法中

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-28
      • 1970-01-01
      • 1970-01-01
      • 2019-08-25
      • 2023-04-06
      • 1970-01-01
      • 2019-02-24
      • 2021-05-05
      相关资源
      最近更新 更多