2

I use Apollo iOS 0.8 with Xcode 9.3, Swift 4.1 and iOS 11, and initialise Apollo client instance like this:

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

The application works well with all queries and mutations sent to the GraphQL server without a problem, except when the app is in background. As far as I know, with common NSURLSession instance it can be easily solved by switching session configuration to URLSessionConfiguration.background(withIdentifier: "your-session-id").

But when I replace the line

let configuration = URLSessionConfiguration.default

with

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

the app starts crashing with this error: Terminating app due to uncaught exception 'NSGenericException', reason: 'Completion handler blocks are not supported in background sessions. Use a delegate instead.'

What's the best way to resolve this error when using Apollo GraphQL or is there any other way to communicate with a GraphQL server in background?

4

1 回答 1

4

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配置和更多功能的实现。

于 2018-05-04T15:57:43.727 回答