Logo for tanaschita.com

Getting started with Apollo iOS for GraphQL in Swift

Learn how to integrate GraphQL into a Swift application using Apollo iOS.

12 Feb 2024 · 8 min read

In this article on GraphQL essentials, we looked at what GraphQL is and how it differs from a REST approach.

Now, we are going to look at how we can implement a networking GraphQL layer by using Apollo in our iOS applications.

Let's get started.

Sponsorship logo
Preparing for a technical iOS job interview - updated for iOS 17
Check out my book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift, SwiftUI, Combine, HTTP Networking, Authentication, SwiftData & Core Data, Concurrency with async/await, Security, Automated Testing, Machine Learning and more.
LEARN MORE

Apollo iOS is an open-source GraphQL framework for iOS written in Swift. We can use it to automatically generate Swift queries from a GraphQL scheme and GraphQl query files.

To begin using Apollo iOS, the following steps are recommended:

  1. Adding Apollo as dependency using the Swift Package Manager

  2. Installing Codegen CLI provided by Apollo which helps with schema introspection and code generation.

  3. Configuring code generation options by creating the configuration file apollo-codegen-config.json.

  4. Downloading a schema from the GraphQL endpoint which Apollo needs to generate Swift types.

  5. Creating queries which will be converted to Swift types by Apollo.

  6. Execute queries and handle responses by using pregenerated functions.

Let's look at each step in more detail.

1. Adding Apollo dependency

Apollo offers the common options to install the library into an iOS project. For example by using the Swift Package Manager, we can add the following package: https://github.com/apollographql/apollo-ios.git.

Adding Apollo package with SPM.
Adding Apollo package with SPM

Within the dialog which offers different packages to install, only choose Apollo for now:

Choosing Apollo package.
Choosing Apollo package.

2. Installing Codegen CLI

The Apollo iOS SPM package includes the Codegen CLI as an executable target. To install it, we can right-click on the project in Xcode's file explorer using the Install CLI command:

Installing Codegen CLI.
Installing Codegen CLI.

After installing the plugin, a symbolic link to the Codegen CLI is created in the project's root folder. We can now run the CLI from the command line with ./apollo-ios-cli which we'll use in later steps.

Note that apollo-ios-cli only works if the compiled CLI executable exists which is located in Xcode's Derived Data or .build folder. If these are cleared, we need to rerun the Install CLI plugin to rebuild the executable.

3. Configuring code generation options

As a next step, we create a configuration file named apollo-codegen-config.json. The Codegen CLI uses this file to configure the code generation engine.

We can use the Codegen Cli to create and prefill this file for us with default values by running:

./apollo-ios-cli init --schema-namespace ExampleAppAPI --module-type swiftPackageManager

The command above generates the apollo-codegen-config.json file in our project's root folder with the following content:

{
"schemaNamespace" : "ExampleAppAPI",
"input" : {
"operationSearchPaths" : [
"**/*.graphql"
],
"schemaSearchPaths" : [
"**/*.graphqls"
]
},
"output" : {
"testMocks" : {
"none" : {
}
},
"schemaTypes" : {
"path" : "./exampleAppAPI",
"moduleType" : {
"swiftPackageManager" : {
}
}
},
"operations" : {
"inSchemaModule" : {
}
}
}
}

This default configuration will:

  • find all GraphQL schema files ending with .graphqls within our project directory.
  • find all GraphQL query files ending with .graphql within our project directory.
  • generate Swift code for schema types and queries in a directory named ExampleAppAPI when we use the CLI to generate code.

Before we can generate code, we need a GraphQL schema. Let's look at how to download it.

4. Downloading a GraphQL schema

A GraphQL schema serves as a contract between the client and the server, defining how clients can query or mutate data.

We can download the schema with the Codegen CLI by using the following command:

./apollo-ios-cli fetch-schema

The above command won't work yet. First, we need to add info to the configuration file about where to fetch the schema:

"schemaDownloadConfiguration": {
"downloadMethod": {
"introspection": {
"endpointURL": "http://localhost:4000/graphql",
"httpMethod": {
"POST": {}
},
"includeDeprecatedInputValues": false,
"outputFormat": "SDL"
}
},
"downloadTimeout": 60,
"headers": [],
"outputPath": "./graphql/schema.graphqls"
}

Now, after running fetch-schema we should see a graphql folder in the project directory containing a schema.graphqls file.

5. Creating queries

Now, we can start creating queries, for example by copying them from the Apollo Sandbox. To add a query to an iOS project, we at first create a new file with a .graphql extension and then paste the query into it, for example:

RecipeFeedQuery.graphql

query RecipeFeed {
recipeFeed {
id
imageUrl
name
creator {
id
profile {
caption
imageUrl
name
}
}
}
}

6. Executing queries and handle responses

Finally, after building the project, we can now execute the query by using functions Apollo generated for us:

import Apollo
import ExampleAppAPI
let apolloClient = ApolloClient(url: endpointUrl)
apolloClient.fetch(query: RecipeFeedQuery()) { result in
switch result {
case .success(let response):
print(response.data?.recipeFeed)
case .failure(let error):
print(error)
}
}
Sponsorship logo
Preparing for a technical iOS job interview - updated for iOS 17
Check out my book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift, SwiftUI, Combine, HTTP Networking, Authentication, SwiftData & Core Data, Concurrency with async/await, Security, Automated Testing, Machine Learning and more.
LEARN MORE

Newsletter

Image of a reading marmot
Subscribe

Like to support my work?

Say hi

Related tags

Articles with related topics

graphql

networking

swift

ios

GraphQL essentials for iOS development

Understand the concept behind GraphQL in context of iOS development.

22 Apr 2024 · 12 min read

Latest articles and tips

© 2024 tanaschita.com

Privacy policy

Impressum