Design+Code logo

Quick links

Suggested search

Install Apollo

All the instructions about installation can be found on the Apollo GraphQL documentation page.

Install the Apollo Swift Package by entering the Apollo iOS Github's repository link (https://github.com/apollographql/apollo-ios.git) in the Add Package Dependency window.

1

Select the version Up to Next Minor, as specified in their documentation.

2

Once the package has been fetched, check only the Apollo option as you'll only need this package. Then, click Finish.

3

Add your schema

In order to run your query, Apollo requires a schema.json file. You can download your schema by downloading the Apollo CLI (if you don't have it already) and running the following command in your terminal - and replacing the link with your API link:

apollo schema:download --endpoint=http://localhost:8080/graphql schema.json

Note: This schema file should be added in the folder where most of your code is, but not in the .xcodeproj folder nor the .xcworkspace folder. It's safe to put it in the Shared folder.

For this tutorial, we will use a sample schema from Apollo. Run the following command in your terminal to download the schema:

apollo schema:download --endpoint=https://apollo-fullstack-tutorial.herokuapp.com/ schema.json

4

This command will download the schema and save it into the folder you currently are. Don't forget to drag and drop it into the Shared folder of your Xcode project.

Create a GraphQL query

Next, you'll need to create a GraphQL query to fetch data. You can use the schema's playground to test your query before putting it in your project. Below is a valid query using Apollo's sample schema.

Note: Apollo requires that each query has a unique name. In this case, this query is named LaunchList.

query LaunchList {
  launches {
    launches {
      id
      site
      mission {
        name
      }
      rocket {
        id
        name
        type
      }
      isBooked
    }
  }
}

If your query returns a result in the playground, it's safe to put it in your project. Create a new file and select Empty. Name it LaunchQuery.graphql and paste the query in there.

Add a code generation on build phase

Navigate to your project settings.

5

For each target (iOS, macOS), go to the Build Phases tab and add a new Build Phase by clicking on the + sign at the top. In this tutorial, we'll only focus on the iOS target.

6

Click on New Run Script Phase.

7

A new Run script will appear. Change its name to Generate Apollo GraphQL API

8

Then, drag and drop Generate Apollo GraphQL API just after Dependencies and before Compile Sources. The order of the scripts should look like this:

9

Next, copy the following code and add it in the Generate Apollo GraphQL API that you just created.

Note 1: If you are using another Package manager than Swift Package Manager, visit Apollo GraphQL's documentation to copy and paste the right script.

Note 2: If you put your schema.json file in the Shared folder, change ${TARGET_NAME} to Shared.

# Go to the build root and search up the chain to find the Derived Data Path where the source packages are checked out.
DERIVED_DATA_CANDIDATE="${BUILD_ROOT}"

while ! [ -d "${DERIVED_DATA_CANDIDATE}/SourcePackages" ]; do
  if [ "${DERIVED_DATA_CANDIDATE}" = / ]; then
    echo >&2 "error: Unable to locate SourcePackages directory from BUILD_ROOT: '${BUILD_ROOT}'"
    exit 1
  fi

  DERIVED_DATA_CANDIDATE="$(dirname "${DERIVED_DATA_CANDIDATE}")"
done

# Grab a reference to the directory where scripts are checked out
SCRIPT_PATH="${DERIVED_DATA_CANDIDATE}/SourcePackages/checkouts/apollo-ios/scripts"

if [ -z "${SCRIPT_PATH}" ]; then
    echo >&2 "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}"
"${SCRIPT_PATH}"/run-bundled-codegen.sh codegen:generate --target=swift --includes=./**/*.graphql --localSchemaFile="schema.json" API.swift

10

Then, try to build your application. If the build succeeded, then you're all set and ready to work with the data!

Note: When you build, the API.swift file is generated automatically. So every time you change something in your query, if API.swift isn't automatically modified, you'll need to add the file to your Xcode project again.

Work with previews

The preview might always pause after adding the Apollo script. To prevent this from happening, check the For install builds only option, just below the script. Remember to uncheck it every time you add a new query or update a query so Apollo can re-generate the API.swift file.

11

Conclusion

In the next part of this three-part Apollo GraphQL tutorial, we'll learn how to make the network call and process the data we get from the server into our own data model type. See you in the next section!

Learn with videos and source files. Available to Pro subscribers only.

Purchase includes access to 50+ courses, 320+ premium tutorials, 300+ hours of videos, source files and certificates.

BACK TO

Archive a Build in Xcode

READ NEXT

Apollo GraphQL Part 2

Templates and source code

Download source files

Download the videos and assets to refer and learn offline without interuption.

check

Design template

check

Source code for all sections

check

Video files, ePub and subtitles

Videos

Assets

ePub

Subtitles

1

Firebase Auth

How to install Firebase authentification to your Xcode project

8:18

2

Read from Firestore

Install Cloud Firestore in your application to fetch and read data from a collection

8:01

3

Write to Firestore

Save the data users input in your application in a Firestore collection

5:35

4

Join an Array of Strings

Turn your array into a serialized String

3:33

5

Data from JSON

Load data from a JSON file into your SwiftUI application

5:08

6

HTTP Request

Create an HTTP Get Request to fetch data from an API

6:31

7

WKWebView

Integrate an HTML page into your SwiftUI application using WKWebView and by converting Markdown into HTML

5:25

8

Code Highlighting in a WebView

Use Highlight.js to convert your code blocks into beautiful highlighted code in a WebView

5:11

9

Test for Production in the Simulator

Build your app on Release scheme to test for production

1:43

10

Debug Performance in a WebView

Enable Safari's WebInspector to debug the performance of a WebView in your application

1:57

11

Debug a Crash Log

Learn how to debug a crash log from App Store Connect in Xcode

2:22

12

Simulate a Bad Network

Test your SwiftUI application by simulating a bad network connection with Network Link Conditionner

2:11

13

Archive a Build in Xcode

Archive a build for beta testing or to release in the App Store

1:28

14

Apollo GraphQL Part I

Install Apollo GraphQL in your project to fetch data from an API

6:21

15

Apollo GraphQL Part 2

Make a network call to fetch your data and process it into your own data type

6:43

16

Apollo GraphQL Part 3

Display the data fetched with Apollo GraphQL in your View

5:08

17

Configuration Files in Xcode

Create configuration files and add variables depending on the environment - development or production

4:35

18

App Review

Request an app review from your user for the AppStore

5:43

19

ImagePicker

Create an ImagePicker to choose a photo from the library or take a photo from the camera

5:06

20

Compress a UIImage

Compress a UIImage by converting it to JPEG, reducing its size and quality

3:32

21

Firebase Storage

Upload, delete and list files in Firebase Storage

11:11

22

Search Feature

Implement a search feature to filter through your content in your SwiftUI application

9:13

23

Push Notifications Part 1

Set up Firebase Cloud Messaging as a provider server to send push notifications to your users

5:59

24

Push Notifications Part 2

Create an AppDelegate to ask permission to send push notifications using Apple Push Notifications service and Firebase Cloud Messaging

6:30

25

Push Notifications Part 3

Tie everything together and test your push notifications feature in production

6:13

26

Network Connection

Verify the network connection of your user to perform tasks depending on their network's reachability

6:49

27

Download Files Locally Part 1

Download videos and files locally so users can watch them offline

6:05

28

Download Files Locally Part 2

Learn how to use the DownloadManager class in your views for offline video viewing

6:02

29

Offline Data with Realm

Save your SwiftUI data into a Realm so users can access them offline

10:20

30

HTTP Request with Async Await

Create an HTTP get request function using async await

6:11

31

Xcode Cloud

Automate workflows with Xcode Cloud

9:23

32

SceneStorage and TabView

Use @SceneStorage with TabView for better user experience on iPad

3:52

33

Network Connection Observer

Observe the network connection state using NWPathMonitor

4:37

34

Apollo GraphQL Caching

Cache data for offline availability with Apollo GraphQL

9:42

35

Create a model from an API response

Learn how to create a SwiftUI model out of the response body of an API

5:37

36

Multiple type variables in Swift

Make your models conform to the same protocol to create multiple type variables

4:23

37

Parsing Data with SwiftyJSON

Make API calls and easily parse data with this JSON package

9:36

38

ShazamKit

Build a simple Shazam clone and perform music recognition

12:38

39

Firebase Remote Config

Deliver changes to your app on the fly remotely

9:05