繁体   English   中英

如何在具有后台会话配置的iOS上正确使用Apollo GraphQL?

[英]How to correctly use Apollo GraphQL on iOS with background session configuration?

我将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.'以下错误Terminating app due to uncaught exception 'NSGenericException', reason: 'Completion handler blocks are not supported in background sessions. Use a delegate instead.'开始崩溃: Terminating app due to uncaught exception 'NSGenericException', reason: 'Completion handler blocks are not supported in background sessions. Use a delegate instead.' Terminating app due to uncaught exception 'NSGenericException', reason: 'Completion handler blocks are not supported in background sessions. Use a delegate instead.'

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

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

假设您有一个NetworkTransport实现,该实现将URLSession实现与后台会话配置包装URLSession

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

然后,您可以ApolloClient以下方式初始化ApolloClient

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

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

如果您在应用程序中使用Alamofire ,则还可以使用ApolloAlamofire库,该库提供NetworkTransport的实现,并支持后台URLSession配置和其他一些功能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM