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:
import Foundationimport Apolloclass 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.defaultconfiguration.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
- Build apps and APIs 10x faster
- Built-in authorization and caching
- 8x more performant than hand-rolled APIs