5. Execute your first query


To use the generated operations in RocketReserverAPI, you first create an instance of ApolloClient. 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

  1. Create a new Swift file within RocketReserver called Network.swift. Set the target to RocketReserver and add import Apollo to the top of the file.

  2. Now add the following code into the file:

Swift
Network.swift
1class Network {
2  static let shared = Network()
3
4  private(set) lazy var apollo = ApolloClient(url: URL(string: "https://apollo-fullstack-tutorial.herokuapp.com/graphql")!)
5}

Implement the query

To make sure your ApolloClient instance is communicating correctly with the server, go to LaunchListViewModel, add these imports, then add the following code to the init() method just below the TODO:

Swift
LaunchListViewModel.swift
1import Apollo
2import RocketReserverAPI
3
4...
5
6init() {
7    // TODO (Section 13 - https://www.apollographql.com/docs/ios/tutorial/tutorial-subscriptions#use-your-subscription)
8    Network.shared.apollo.fetch(query: LaunchListQuery()) { result in
9        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:

Query console log output, beginning with 'Success! Result: GraphQLResult...'

This means the request was correctly executed and you now have a list of launch sites 🚀🚀🚀.

Go ahead and remove the code added to the init() method so there is just the TODO for later:

Swift
LaunchListViewModel.swift
1init() {
2    // TODO (Section 13 - https://www.apollographql.com/docs/ios/tutorial/tutorial-subscriptions#use-your-subscription)
3}

Next, let's connect this data to your UI