iOS

Using GraphQL Apollo iOS Client in a Swift Project

Introduction

In this section you will learn how to install the Apollo iOS Client on your Swift project and query data from Back4app using it.

Prerequisites

To complete this quickstart, you need:

  • Xcode.
  • An app created at Back4App.
  • A Class with some data stored (so you can retrieve it).

Step 1 - Getting Apollo Client into your XCode Project

The easiest way to integrate the Apollo iOS Client is by using CocoaPods. In order to integrate it, follow these steps:

  1. Create your XCode project and in the same folder of your .xcodeproj file, create a new file named Podfile

    Podfile

  2. Edit the Podfile file and add the following code, changing the string YourProjectNameHere to your project’s name:
     # Uncomment the next line to define a global platform for your project
     platform :ios, '12.0'
    
     target 'YourProjectNameHere' do
     # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
     use_frameworks!
    
     # Pods for ConferencePlanner
     pod 'Apollo'
    
     end
    
  3. Save the file and open a terminal. Go to that folder and type:
     pod install
    

    Podfile

  4. When the installation finishes, you should have a new file with the format .xcworkspace. Open that file with Xcode.

Podfile

Step 2 - Retrieve your Schemas

You need a file name schema.json containing the Schemas for your GraphQL endpoint. There are two ways for you to retrieve your full Schema:

  1. Using the Back4app GraphQL Console

  2. Using Apollo

We will discuss both. Choose the one you like the best.

Step 2.1 - Retrieve your Schemas with the Back4app GraphQL Console

Go to your GraphQL Console for the App you want to retrieve the schema from and on, the right hand under the Schema tab, click the Download button.

Podfile

Step 2.2 - Retrieve your Schemas with Apollo

If you prefer to use Apollo, first you have to install the Desktop version by typing:

npm install -g apollo

Then, run the following command replacing the values for the headers with your AppId and Masterkey:

apollo client:download-schema --endpoint=https://parseapi.back4app.com/graphql --header="X-Parse-Application-Id: YourAppIdHere" --header="X-Parse-Master-Key: YourMasterKeyHere"

This will generate a schema.json file as output

Step 3 - Add your Schema.json file to the project

Add the schema.json file that you downloaded or retrieved to your project in the root directory. This is the same folder where your AppDelegate.swift file is located

Podfile

Step 4 - Create your GraphQL files

You now can create your GraphQL files with your files and mutations.
Those file must have the .graphql extension and cointain at least one query or mutation in order for Apollo to crate the Swift code from.

A useful convention is to colocate queries, mutations or fragments with the Swift code that uses them by creating <name>.graphql next to <name>.swift.

If you don’t have pre-existing .graphql files in your file tree, create a very simple query and add it to a .graphql file in your file tree so that when you run the code generation build step, it actually finds something. If you don’t, you’ll get the error No operations or fragments found to generate code for.

Here is a simple query that as an example, that returns Parse users:

query findAllUsers{
  objects{
    find_User{
      count
      results{
        username
      }
    }
  }
}

Add that file to your Target directory at the same level your schema.json file is:

Podfile

Step 5 - Add a code generation build step

You can invoke apollo as part of the Xcode build process, which will retrieve and update the schema.json file automatically so your classes will always reflect any changes you make by calling the check-and-run-apollo-cli.sh wrapper script.

The wrapper checks if the version of Apollo installed on your system is compatible with the framework version in your project.
If you don’t check that, you could potentially generate code that is incompatible with the runtime code in the framework.

The steps are:

  1. On your application target’s Build Phases settings tab, click the + icon and choose New Run Script Phase.

  2. In the created Run Script, change its name to Generate Apollo GraphQL API.

  3. Drag this new run script just above Compile Sources in your list of Build Phases so that it executes before your code is compiled.

  4. Add the following to the Run Script:

    SCRIPT_PATH="${PODS_ROOT}/Apollo/scripts"
    cd "${SRCROOT}/${TARGET_NAME}"
    "${SCRIPT_PATH}"/check-and-run-apollo-cli.sh codegen:generate --target=swift --includes=./**/*.graphql --localSchemaFile="schema.json" API.swift
    

If you are using XCode 11 Beta, add this script instead:

# Go to the build root and go back up to where SPM keeps the apollo iOS framework checked out.
cd "${BUILD_ROOT}"
cd "../../SourcePackages/checkouts/apollo-ios/scripts"

APOLLO_SCRIPT_PATH="$(pwd)"

if [ -z "${APOLLO_SCRIPT_PATH}" ]; then
    echo "error: Couldn't find the CLI script in your checked out SPM packages; make sure to add the framework to your project."
    exit 1
fi

cd "${SRCROOT}/${TARGET_NAME}"
"${APOLLO_SCRIPT_PATH}"/check-and-run-apollo-cli.sh codegen:generate --target=swift --includes=./**/*.graphql --localSchemaFile="schema.json" API.swift

Step 6 - Build and add your API file to the target

Build your project and a file named API.swift should be created on your Target’s directory:

Podfile

Drag the generated API.swift file to your target and make sure to uncheck the “Copy Files If Needed” checkbox:

Podfile

Make sure you checked all the Targets the API file needs to be included in.

Podfile

Step 7 - Configure the Client

Now on your ViewController.swift, create your Apollo configuration and change your AppId and ClientKey values:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let apollo: ApolloClient = {
    let configuration = URLSessionConfiguration.default
    configuration.httpAdditionalHeaders = [
        "X-Parse-Application-Id": "YourAppIdHere",
        "X-Parse-Client-Key": "YourClientKeyHere"
    ]

    let url = URL(string: "https://parseapi.back4app.com/graphql")!

    return ApolloClient(
        networkTransport: HTTPNetworkTransport(
            url: url,
            configuration: configuration
        )
    )
}()

Step 8 - Configure the Client

On your viewDidLoad, call your GraphQL query from the Apollo client:

1
2
3
4
apollo.fetch(query: FindAllUsersQuery()) { result in
    guard let data = try? result.get().data else { return }
    print(data.objects?.findUser.results[0].username)
}

If you have any users in your User class, the first one (index 0) should be retrieved:

Podfile

Optional Step - Get syntax highlighting

You can have GraphQL syntax highlighting on XCode if you wish. To achieve that:

  1. Clone the xcode-apollo repository to your computer.

  2. Close Xcode if it is currently running.

  3. You may need to create these folders inside of ~/Library/Developer/Xcode:
    mkdir ~/Library/Developer/Xcode/Plug-ins ~/Library/Developer/Xcode/Specifications
    
  4. Copy GraphQL.ideplugin to ~/Library/Developer/Xcode/Plug-ins.
    cp -R GraphQL.ideplugin ~/Library/Developer/Xcode/Plug-ins
    
  5. Copy GraphQL.xclangspec to ~/Library/Developer/Xcode/Specifications.
    cp -R GraphQL.xclangspec ~/Library/Developer/Xcode/Specifications
    

You may receive a warning the first time you start up Xcode after installing these add-ons. Once you agree to load the plugin, you will no longer see this warning.