Getting Started with Apollo iOS
Integrate Apollo iOS into your app
Upgrading from Apollo iOS 1.x? See the Apollo iOS 2.0 Migration Guide for detailed migration instructions.
Follow the steps below to add Apollo iOS to your app:
1. Install the Apollo frameworks
You can add Apollo iOS into your project using Swift Package Manager.
SPM with Package.swift
Package.swift file, you can add Apollo iOS as a dependency there.Add Apollo iOS to your dependencies list
1dependencies: [
2 .package(
3 url: "https://github.com/apollographql/apollo-ios.git",
4 .upToNextMajor(from: "2.0.0")
5 ),
6],Link the Apollo product to your package target
Any targets in your application that will useApolloClient need to have a dependency on the Apollo product.1.target(
2 name: "MyApp",
3 dependencies: [
4 .product(name: "Apollo", package: "apollo-ios"),
5 ]
6)Note: Targets that only use Apollo's generated models don't need to be linked to the Apollo product.SPM with Xcode Project
https://github.com/apollographql/apollo-ios.git) into the search bar, then select the apollo-ios package that appears:Note: Xcode might not automatically select the latest version number, please check.
Apollo library for now. You can always add other packages later if you need them.Notes:Then, click Add Package.
- Do not select the
Apollo-Dynamicproduct unless your project is configured to use dynamic linking of the Apollo iOS framework. Most projects do not need to link to this product.- Do not select the
apollo-ios-clipackage. This product is the CLI executable for code generation. If you link it to your project as a dependency it will cause build errors.
2. Add a schema file to your target directory
For Apollo iOS to generate models for your GraphQL operations, you need a local copy of your GraphQL server's schema.
See Downloading a schema for more details.
3. Create .graphql files for your GraphQL operations
Apollo iOS generates code from the GraphQL queries and mutations defined in your target's files. To use Apollo iOS, you'll need to define at least one operation GraphQL operation.
GraphQL operation and fragment definitions traditionally have the file extension .graphql. The generated models will have the file extension .graphql.swift.
See Defining operations for more details.
4. Setup and run code generation
Apollo iOS code generation uses your .graphql files to generate API code that helps you execute GraphQL operations and parse and cache operation responses.
Whenever you make changes to your GraphQL operation definitions, you'll need to run the code generation engine to re-generate your GraphQL models.
The easiest way to do this is with the Codegen CLI provided with Apollo iOS.
For more advanced usage and configuration (including use with modularized projects), see Code Generation.
To use Apollo's code generation and schema downloader from within any Swift script or library, check out Running code generation in Swift code.
SPM with Package.swift
Install the Codegen CLI
The Apollo iOS SPM package includes the Codegen CLI as an executable target. This ensures you always have a valid CLI version for your Apollo iOS version.To simplify accessing the Codegen CLI, you can run the includedapollo-cli-install SPM plugin. This plugin builds the CLI and creates a symbolic link to the executable in your project root.If using a Package.swift file, you can install the CLI by running:1swift package --allow-writing-to-package-directory apollo-cli-installapollo-ios-cli) in your project root folder. You can now run the CLI from the command line using ./apollo-ios-cli.Note: Because theapollo-ios-cliin your project root is only a symbolic link, it only works if the compiled CLI executable exists. This is generally located in your Xcode Derived Data or the.buildfolder. If these are cleared, you can rerun the Install CLI plugin to rebuild the CLI executable.
Initialize the code generation configuration
The Codegen CLI uses a JSON file to configure the code generation engine. You can use the Codegen CLI'sinit command to create this file with default values.From your project's root directory, run the following command with your customized values:1./apollo-ios-cli init --schema-namespace ${MySchemaName} --module-type ${ModuleType}${MySchemaName}provides a name for the namespace of your generated schema files.${ModuleType}configures how your generated schema types are included in your project.This is a crucial decision to make before configuring code generation. To determine the right option for your project, see Project Configuration.To get started quickly, you can use the
embeddedInTargetoption. UsingembeddedInTarget, you must supply a target name using the--target-namecommand line option.
apollo-codegen-config.json file.Configure code generation options
Open yourapollo-codegen-config.json file to start configuring code generation for your project.The default configuration will:- Find all GraphQL schema files ending with the file extension
.graphqlswithin your project directory. - Find all GraphQL operation and fragment definition files ending with the file extension
.graphqlwithin your project directory. - Generate Swift code for the schema types in a directory with the
schema-nameprovided. - Generate Swift code for the operation and fragment models in a subfolder within the schema types output location.
Run code generation
From your project's root directory, run:1./apollo-ios-cli generate.graphql.swift.Add the generated schema and operation files to your target
By default, a directory containing your generated schema files is within a directory with the schema name you provided (i.e.,MySchemaName). Your generated operation and fragment files are in a subfolder within the same directory.If you created your target in an Xcode project or workspace, you'll need to manually add the generated files to your target.Note: Because adding generated files to your Xcode targets must be done manually each time you generate new files, we highly recommend defining your project targets with SPM. Alternatively, you can generate your operations into the package that includes your schema files. For more information see the documentation for Code Generation Configuration.
SPM with Xcode Project
Install the Codegen CLI
The Apollo iOS SPM package includes the Codegen CLI as an executable target. This ensures you always have a valid CLI version for your Apollo iOS version.To simplify accessing the Codegen CLI, you can run the includedInstallCLI SPM plugin.This plugin builds the CLI and creates a symbolic link to the executable in your project root.If you use Swift packages through Xcode, you can right-click on your project in the Xcode file explorer, revealing an Install CLI plugin command. Selecting this command presents a dialog allowing you to grant the plugin "write" access to your project directory.apollo-ios-cli) in your project root folder. You can now run the CLI from the command line with ./apollo-ios-cli.Note: Because theapollo-ios-cliin your project root is only a symbolic link, it only works if the compiled CLI executable exists. This is generally located in your Xcode Derived Data or the.buildfolder. If these are cleared, you can rerun the Install CLI plugin to rebuild the CLI executable.
Initialize the code generation configuration
The Codegen CLI uses a JSON file to configure the code generation engine. You can use the Codegen CLI'sinit command to create this file with default values.From your project's root directory, run the following command with your customized values:1./apollo-ios-cli init --schema-namespace ${MySchemaName} --module-type ${ModuleType}${MySchemaName}provides a name for the namespace of your generated schema files.${ModuleType}configures how your generated schema types are included in your project.This is a crucial decision to make before configuring code generation. To determine the right option for your project, see Project Configuration.To get started quickly, you can use the
embeddedInTargetoption. UsingembeddedInTarget, you must supply a target name using the--target-namecommand line option.
apollo-codegen-config.json file.Configure code generation options
Open yourapollo-codegen-config.json file to start configuring code generation for your project.The default configuration will:- Find all GraphQL schema files ending with the file extension
.graphqlswithin your project directory. - Find all GraphQL operation and fragment definition files ending with the file extension
.graphqlwithin your project directory. - Generate Swift code for the schema types in a directory with the
schema-nameprovided. - Generate Swift code for the operation and fragment models in a subfolder within the schema types output location.
Run code generation
From your project's root directory, run:1./apollo-ios-cli generate.graphql.swift.Add the generated schema and operation files to your target
By default, a directory containing your generated schema files is within a directory with the schema name you provided (i.e.,MySchemaName). Your generated operation and fragment files are in a subfolder within the same directory.If you created your target in an Xcode project or workspace, you'll need to manually add the generated files to your target.Note: Because adding generated files to your Xcode targets must be done manually each time you generate new files, we highly recommend defining your project targets with SPM. Alternatively, you can generate your operations into the package that includes your schema files. For more information see the documentation for Code Generation Configuration.
5. Create an ApolloClient
Before you can execute GraphQL operations in your app, you need to initialize an ApolloClient instance.
1import Foundation
2import Apollo
3
4let apolloClient = ApolloClient(url: URL(string: "http://localhost:4000/graphql")!)See Creating a client for more details.
6. Fetch a query
ApolloClient can fetch your generated operation definitions, and return the response as a type-safe generated data model.
For example, if you define a query called HeroName:
1query HeroName {
2 hero {
3 name
4 }
5}Apollo iOS will generate a HeroNameQuery class that you can construct and pass to ApolloClient.fetch(query:):
1Task {
2 do {
3 let response = try await apolloClient.fetch(query: HeroNameQuery())
4 print(response.data?.hero?.name) // Luke Skywalker
5 } catch {
6 print("Error fetching hero: \(error)")
7 }
8}See Fetching data for more details.