5. Execute your first query
To use the generated operations inRocketReserverAPI
, you first create an instance ofApolloClient
. This instance takes your generated code and uses it to make network calls to your server. It's recommended that this instance is a singleton or static instance that's accessible from anywhere in your codebase.
Create an ApolloClient
Create a new Swift file within
RocketReserver
calledNetwork.swift
. Set the target toRocketReserver
and addimport Apollo
to the top of the file.Now add the following code into the file:
1class Network {2 static let shared= Network()34 private(set)lazy var apollo= ApolloClient(url:URL(string:"https://apollo-fullstack-tutorial.herokuapp.com/graphql")!)5}
Implement the query
To make sure yourApolloClient
instance is communicating correctly with the server, go toLaunchListViewModel
, add these imports, then add the following code to theinit()
method just below the TODO:
1import Apollo2import RocketReserverAPI34...56init() {7 // TODO (Section 13 - https://www.apollographql.com/docs/ios/tutorial/tutorial-subscriptions#use-your-subscription)8 Network.shared.apollo.fetch(query:LaunchListQuery()) { resultin9 switch result {10 case .success(let graphQLResult):11 print("Success! Result:\(graphQLResult)")12 case .failure(let error):13 print("Failure! Error:\(error)")14 }15 }16}
Test your query
Build and run your application. The web host might take a few seconds to spin up your GraphQL server if nobody's been using it recently, but once it's up, you should see a response that resembles the following:
This means the request was correctly executed and you now have a list oflaunch sites 🚀🚀🚀.
Go ahead and remove the code added to theinit()
method so there is just the TODO for later:
1init() {2 // TODO (Section 13 - https://www.apollographql.com/docs/ios/tutorial/tutorial-subscriptions#use-your-subscription)3}
Next, let'sconnect this data to your UI