【问题标题】:How to correctly use Apollo GraphQL on iOS with background session configuration?如何在 iOS 上通过后台会话配置正确使用 Apollo GraphQL?
【发布时间】:2023-03-20 02:39:01
【问题描述】:

我将Apollo iOS 0.8 与 Xcode 9.3、Swift 4.1 和 iOS 11 一起使用,并像这样初始化 Apollo 客户端实例:

import Apollo

// ... unrelated code skipped

let configuration = URLSessionConfiguration.default

if let token = keychain.accessToken {
  // Add additional headers as needed
  configuration.httpAdditionalHeaders = [
    "Authorization": "Bearer \(token)"
  ]
}

let graphqlEndpoint = URL("https://sample-server-url/graphql")!
let client = ApolloClient(networkTransport:
  HTTPNetworkTransport(url: graphqlEndpoint, configuration: configuration))

应用程序可以很好地处理发送到 GraphQL 服务器的所有查询和突变,除非应用程序在后台。据我所知,使用常见的NSURLSession 实例可以通过将会话配置切换到URLSessionConfiguration.background(withIdentifier: "your-session-id") 来轻松解决。

但是当我换行时

let configuration = URLSessionConfiguration.default

let configuration = URLSessionConfiguration.background(withIdentifier: "your-session-id")

应用程序开始崩溃并出现以下错误:Terminating app due to uncaught exception 'NSGenericException', reason: 'Completion handler blocks are not supported in background sessions. Use a delegate instead.'

在使用 Apollo GraphQL 时解决此错误的最佳方法是什么,或者是否有其他方法可以在后台与 GraphQL 服务器进行通信?

【问题讨论】:

    标签: ios swift graphql apollo apollo-ios


    【解决方案1】:

    Apollo iOS 提供了一个公共的NetworkTransport 协议,允许覆盖所有网络交互。可以将实现作为参数提供给ApolloClient(networkTransport: NetworkTransport) 初始化程序。

    假设您有一个 NetworkTransport 实现,它使用后台会话配置包装了 URLSession 实现:

    class BackgroundTransport: NetworkTransport {
        public func send<Operation>(operation: Operation,
        completionHandler: @escaping (GraphQLResponse<Operation>?, Error?) -> Void)
        -> Cancellable where Operation: GraphQLOperation {
        // ...
        }
    }
    

    然后你可以这样初始化ApolloClient

    let graphqlEndpoint = URL("https://sample-server-url/graphql")!
    let client = ApolloClient(networkTransport: BackgroundTransport(url: u))
    

    BackgroundTransport 实现可以根据需要进行自定义,包括使用URLSession 委托而不是完成处理程序块,这是后台会话配置的要求。

    如果您在应用中使用Alamofire,您还可以使用ApolloAlamofire 库,该库提供NetworkTransport 的实现,支持后台URLSession 配置和更多功能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-29
      • 1970-01-01
      • 2022-12-14
      • 2020-02-12
      • 2018-03-20
      • 2020-05-14
      • 2020-09-12
      • 2018-05-14
      相关资源
      最近更新 更多