apollo-ios
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseApollo iOS Guide
Apollo iOS 指南
Apollo iOS is a strongly-typed GraphQL client for Apple platforms. It generates Swift types from your GraphQL operations and schema, and ships an async/await client, a normalized cache (in-memory or SQLite-backed), a pluggable interceptor-based HTTP transport that handles queries, mutations, and multipart subscriptions, and an optional WebSocket transport () that can carry any operation type.
graphql-transport-wsApollo iOS 是一款适用于苹果平台的强类型GraphQL客户端。它会根据你的GraphQL操作和架构生成Swift类型,同时提供异步/等待客户端、规范化缓存(基于内存或SQLite)、可插拔的基于拦截器的HTTP传输(处理查询、变更和多部分订阅),以及可选的WebSocket传输(),可承载任何类型的操作。
graphql-transport-wsProcess
流程
Follow this process when adding or working with Apollo iOS:
- Confirm target platforms, GraphQL endpoint(s), and how the schema is sourced.
- Add Apollo iOS via Swift Package Manager and install the .
apollo-ios-cli - Link each target to the correct product (for targets using
Apollo,ApolloClientfor targets that only read generated models).ApolloAPI - Write using the canonical default (
apollo-codegen-config.json,moduleType: swiftPackage); deviate only when the project has a specific constraint.operations: relative - Run codegen and wire it into the build.
- Create a single shared and inject it via SwiftUI
ApolloClient.Environment - Implement operations (queries, mutations, subscriptions) from view models.
@Observable - Add interceptors for auth and logging.
- When the first test that needs is written, flip
Mock<Type>inoutput.testMocksfromapollo-codegen-config.jsontonone(orswiftPackage), regenerate, and link the mocks target to the test target.absolute
添加或使用Apollo iOS时,请遵循以下流程:
- 确认目标平台、GraphQL端点以及架构的获取方式。
- 通过Swift Package Manager添加Apollo iOS并安装。
apollo-ios-cli - 将每个目标链接到正确的产品(使用的目标链接
ApolloClient,仅读取生成模型的目标链接Apollo)。ApolloAPI - 使用标准默认配置(,
moduleType: swiftPackage)编写operations: relative;仅当项目有特定限制时才偏离该配置。apollo-codegen-config.json - 运行代码生成并将其接入构建流程。
- 创建单个共享的并通过SwiftUI
ApolloClient注入。Environment - 从视图模型实现操作(查询、变更、订阅)。
@Observable - 添加用于认证和日志的拦截器。
- 当编写第一个需要的测试时,将
Mock<Type>中的apollo-codegen-config.json从output.testMocks改为none(或swiftPackage),重新生成代码,并将模拟目标链接到测试目标。absolute
Reference Files
参考文件
- Setup — Install the SDK and CLI, link the right product (/
Apollo/ApolloAPI/ApolloSQLite/ApolloWebSocket) to each target, generate the canonicalApolloTestSupport, download the schema, run initial codegen, initializeapollo-codegen-config.json, wire it into SwiftUI.ApolloClient - Codegen — Full reference:
apollo-codegen-config.json(schemaTypes.moduleType/swiftPackage/embeddedInTarget) andother(operations/relative/inSchemaModule) with tradeoffs and fragment-sharing patterns, renaming generated types, test mocks, Swift 6 / MainActor flags, and why you should not auto-run codegen from an Xcode build phase.absolute - Custom Scalars — Default behavior (generated as ), when to replace the default, conforming to
typealias <Scalar> = String, and canonical patterns forCustomScalarType,Date, andURL.Decimal - Operations — Queries, mutations, watchers, cache policies, error handling, and SwiftUI view-model patterns with async/await.
@Observable - Caching — Choosing between in-memory and SQLite cache, declaring cache keys with the directive, programmatic cache keys as advanced fallback, watching the cache, manual reads/writes.
@typePolicy - Interceptors — The four interceptor protocols, building a custom , auth token interceptor, logging, retry, APQ.
InterceptorProvider - Subscriptions — Choosing between HTTP multipart and WebSocket transports, wiring,
SplitNetworkTransportauth, pause/resume on scene phase, consuming subscriptions from SwiftUI.connection_init - Testing — , generated
ApolloTestSupportfixtures, the protocol-wrapper pattern for testable view models, integration testing with a fakeMock<Type>, testing watchers.NetworkTransport
- 设置 — 安装SDK和CLI,为每个目标链接正确的产品(/
Apollo/ApolloAPI/ApolloSQLite/ApolloWebSocket),生成标准的ApolloTestSupport,下载架构,运行初始代码生成,初始化apollo-codegen-config.json,并将其接入SwiftUI。ApolloClient - 代码生成 — 完整参考:
apollo-codegen-config.json(schemaTypes.moduleType/swiftPackage/embeddedInTarget)和other(operations/relative/inSchemaModule)的权衡与片段共享模式、重命名生成的类型、测试模拟、Swift 6 / MainActor标志,以及为何不应从Xcode构建阶段自动运行代码生成。absolute - 自定义标量 — 默认行为(生成为)、何时替换默认值、遵循
typealias <Scalar> = String,以及CustomScalarType、Date和URL的标准模式。Decimal - 操作 — 查询、变更、监视器、缓存策略、错误处理,以及结合async/await的SwiftUI 视图模型模式。
@Observable - 缓存 — 在内存缓存和SQLite缓存之间选择,使用指令声明缓存键,将程序化缓存键作为高级备选方案,监听缓存,手动读取/写入。
@typePolicy - 拦截器 — 四种拦截器协议、构建自定义、认证令牌拦截器、日志、重试、APQ。
InterceptorProvider - 订阅 — 在HTTP多部分传输和WebSocket传输之间选择、配置、
SplitNetworkTransport认证、场景阶段的暂停/恢复、从SwiftUI消费订阅。connection_init - 测试 — 、生成的
ApolloTestSupport测试数据、用于可测试视图模型的协议包装模式、使用模拟Mock<Type>进行集成测试、测试监视器。NetworkTransport
Scripts
脚本
- list-apollo-ios-versions.sh — List published Apollo iOS tags. Use this to find the latest version before writing version-pinned SPM dependencies.
- list-apollo-ios-versions.sh — 列出已发布的Apollo iOS标签。在编写固定版本的SPM依赖项之前,使用此脚本查找最新版本。
Key Rules
核心规则
- Use Apollo iOS v2+. v1.x and v0.x are legacy — do not target them for new work.
- Install via Swift Package Manager. CocoaPods and Carthage are not the recommended distribution mechanism for apollo-ios.
- Default the codegen config to and
moduleType: swiftPackage(see Setup). This shape works for single-target and multi-module apps alike. Deviate only when the project cannot use SPM or has specific fragment-sharing needs (see Codegen).operations: relative - Name the generated schema module after the project, using the convention (e.g.
<ProjectName>APIfor a project calledRocketReserverAPI). Derive the project name fromRocketReserver/ thePackage.swift/ the app product name — never ship the.xcodeprojplaceholder. If the project name is not obvious, ask the user withMyAPI.AskUserQuestion - Target linking is a per-target decision made as modules grow — there is no upfront decision to make. Link to targets using
Apollo; linkApolloClientto targets that only consume generated response models.ApolloAPI - Keep ,
schema.graphqlsoperation files, and.graphqlin source control so builds are reproducible.apollo-codegen-config.json - Regenerate code after every schema or operation change. Never hand-edit generated files.
.graphql - Commit the generated Swift files to source control. Do not wire into an Xcode Run Script build phase — it measurably slows compile times on every build. Regenerate manually or via a dedicated script alias.
apollo-ios-cli generate - Generate test mocks lazily. The canonical codegen config ships with . Flip it on (and regenerate) only when the first test that needs
output.testMocks: { "none": {} }is being written — see Testing.Mock<Type> - Create a single shared per endpoint. Inject it via SwiftUI
ApolloClient; never construct a new client per request.Environment - Prefer schema directives over programmatic cache key resolution when declaring cache keys for types.
@typePolicy - Put auth (attach token + refresh on 401 + retry) in a single . Attach via
GraphQLInterceptor, detect 401 viarequest.additionalHeaders["Authorization"], and trigger the retry by throwing.mapErrors. Always pair withRequestChain.Retry(request:)as a safety-net cap. ReserveMaxRetryInterceptorfor purely HTTP-scoped headers (HTTPInterceptor,User-Agent). Never put auth or retry in view code.Accept-Encoding - In SwiftUI, scope fetch s to
Taskso they cancel automatically when the view disappears..task { } - If Xcode MCP tools are available in the agent environment (typically exposed as ,
mcp__xcode__BuildProject,mcp__xcode__RunSomeTests, etc.), prefer them over rawmcp__xcode__XcodeListNavigatorIssuesfor building, running tests, and inspecting build issues after regenerating code.xcodebuild
- 使用Apollo iOS v2+。v1.x和v0.x为旧版本——新开发工作请勿使用这些版本。
- 通过Swift Package Manager安装。CocoaPods和Carthage不是apollo-ios推荐的分发机制。
- 将代码生成配置默认设置为和
moduleType: swiftPackage(参见设置)。此配置适用于单目标和多模块应用。仅当项目无法使用SPM或有特定的片段共享需求时才偏离该配置(参见代码生成)。operations: relative - 按照的约定,以项目名称命名生成的架构模块(例如,名为
<ProjectName>API的项目对应RocketReserver)。从RocketReserverAPI/Package.swift/ 应用产品名称中获取项目名称——切勿使用.xcodeproj占位符。如果项目名称不明确,请使用MyAPI询问用户。AskUserQuestion - 目标链接是随着模块增长而做出的逐目标决策——无需提前决定。为使用的目标链接
ApolloClient;为仅使用生成的响应模型的目标链接Apollo。ApolloAPI - 将、
schema.graphqls操作文件和.graphql纳入版本控制,确保构建可重现。apollo-codegen-config.json - 每次架构或操作变更后重新生成代码。切勿手动编辑生成的文件。
.graphql - 将生成的Swift文件提交到版本控制。不要将接入Xcode Run Script构建阶段——这会显著减慢每次构建的编译时间。手动重新生成或通过专用脚本别名执行。
apollo-ios-cli generate - 延迟生成测试模拟。标准代码生成配置默认。仅当编写第一个需要
output.testMocks: { "none": {} }的测试时才启用它(并重新生成代码)——参见测试。Mock<Type> - 为每个端点创建单个共享的。通过SwiftUI
ApolloClient注入;切勿为每个请求构造新的客户端。Environment - 声明类型的缓存键时,优先使用架构指令而非程序化缓存键解析。
@typePolicy - 将认证(附加令牌 + 401时刷新 + 重试)放在单个中。通过
GraphQLInterceptor附加令牌,通过request.additionalHeaders["Authorization"]检测401,通过抛出.mapErrors触发重试。始终搭配RequestChain.Retry(request:)作为安全上限。将MaxRetryInterceptor仅用于纯HTTP范围的头信息(HTTPInterceptor、User-Agent)。切勿在视图代码中处理认证或重试逻辑。Accept-Encoding - 在SwiftUI中,将获取数据的限定在
Task范围内,以便视图消失时自动取消任务。.task { } - 如果代理环境中提供了Xcode MCP工具(通常以、
mcp__xcode__BuildProject、mcp__xcode__RunSomeTests等形式暴露),则优先使用这些工具而非原始mcp__xcode__XcodeListNavigatorIssues来构建、运行测试,以及重新生成代码后检查构建问题。xcodebuild