Subscription

When we had initially set up Apollo, we used just the network transport. But subscriptions is an advanced use case which needs more configuration. So we have to add ApolloWebSocket. Add apollowebsocket.framework and starscream.framework from your Carthage/Build/IOS to libraries.

Now we need to update our ApolloClient instance to point to the subscription server.

Open Todo/NetworkManager.swift and update the following:

githubTodo/NetworkManager.swift
import Foundation
import Apollo
class NetworkManager {
static let shared = NetworkManager()
let graphEndpoint = "https://hasura.io/learn/graphql"
+ let graphWSEndpoint = "wss://hasura.io/learn/graphql"
var apolloClient : ApolloClient?
private init (){
}
func setApolloClient(accessToken: String){
self.apolloClient = {
let authPayloads = ["Authorization": "Bearer \(accessToken)"]
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = authPayloads
+ let map: GraphQLMap = authPayloads
+ let wsEndpointURL = URL(string: graphWSEndpoint)!
let endpointURL = URL(string: graphEndpoint)!
+ var request = URLRequest(url: wsEndpointURL)
+ request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
+ let websocket = WebSocketTransport(request: request, sendOperationIdentifiers: false, reconnectionInterval: 30000, connectingPayload: map)
+ let splitNetworkTransport = SplitNetworkTransport(
+ httpNetworkTransport: HTTPNetworkTransport(
+ url: endpointURL,
+ session: URLSession(configuration: configuration)
+ ),
+ webSocketNetworkTransport: websocket
+ )
- return ApolloClient(networkTransport: HTTPNetworkTransport(url: endpointURL, configuration: configuration))
+ return ApolloClient(networkTransport: splitNetworkTransport)
}()
}
}

Note that we are replacing HTTPNetworkTransport with SplitNetworkTransport and hence all GraphQL queries go through a single websocket connection.

Did you find this page helpful?
Start with GraphQL on Hasura for Free
  • ArrowBuild apps and APIs 10x faster
  • ArrowBuilt-in authorization and caching
  • Arrow8x more performant than hand-rolled APIs
Promo
footer illustration
Brand logo
© 2024 Hasura Inc. All rights reserved
Github
Titter
Discord
Facebook
Instagram
Youtube
Linkedin
graphql-handbook