Integrating GraphQL into a SwiftUI App
GraphQL makes it easier to fetch only the data your app needs, and Apollo iOS provides the tools to generate strongly-typed Swift code from your GraphQL schema. Here’s a step-by-step guide to setting up GraphQL in a SwiftUI project.
1. Project Setup
Create a
GraphQL/folder in your Xcode project.This folder will hold:
schema.graphqlsQueries.graphql(and Mutations/Subscriptions if needed)Generated files (
API.swift)
2. Install Apollo iOS
In Xcode, go to File → Add Packages…
Add the package:
Select Apollo and ApolloCodegenLib.
3. Download the Schema
Use the Apollo CLI to download your schema from the GraphQL endpoint:
4. Define Queries
Create a Queries.graphql file in your GraphQL/ folder. Add operations (queries, mutations, subscriptions):
5. Code Generation
Add a Build Phase Script in Xcode:
This generates API.swift with strongly-typed models.
6. Create Apollo Client
Create a Network.swift file for a shared client:
7. Build ViewModels
Each feature should have its own ViewModel. Example:
8. Connect to SwiftUI Views
Use the ViewModel in your SwiftUI view:
9. Mutations (Optional)
You can perform mutations using Apollo:
10. Async/Await (Optional)
Apollo iOS also supports async/await for cleaner code: