GraphQL API 在 Swift 上的应用:分步指南
GraphQL 凭借其灵活性和高效性,正成为现代 API 的标准。与 REST 不同,REST 返回固定数据结构,而 GraphQL 允许您只请求所需的数据。在本指南中,我们将介绍如何使用 Apollo iOS 库,将 GraphQL API 集成到适用于 iOS 和 macOS 的 Swift 应用程序中。您将学习如何执行查询、变更和错误处理。
1. 项目设置与安装 Apollo iOS
第一步是创建一个新的 Xcode 项目,并通过 Swift Package Manager (SPM) 添加 Apollo iOS 依赖项。
步骤 1.1:创建项目
打开 Xcode 并创建一个新项目(iOS App 或 macOS App)。选择 SwiftUI 或 UIKit — 我们的示例将适用于这两种平台。
步骤 1.2:通过 SPM 安装 Apollo iOS
- 在 Xcode 中,转到
File → Add Packages... - 粘贴仓库 URL:
https://github.com/apollographql/apollo-ios.git - 选择最新的稳定版本(例如 1.15.0)并点击 Add Package。
- 在弹出的窗口中,选择您的项目并添加 Apollo 包。
步骤 1.3:生成模式与代码
Apollo iOS 基于 GraphQL 模式进行代码生成。首先,下载您 API 的模式(通常通过 introspection query 进行)。为了测试,我们将使用公共 API Countries GraphQL (https://countries.trevorblades.com)。
在项目根目录下创建 schema.graphqls 文件,并将模式放入其中(您可以通过 GraphQL Playground 获取)。然后,在 Build Phases 中添加生成脚本:
// 示例脚本放在 Build Phases 中if which apollo-ios-cli >/dev/null; then apollo-ios-cli generateelse echo "Apollo CLI 未安装。请通过以下命令安装:brew install apollo-ios-cli"fi通过 Homebrew 安装 CLI: brew install apollo-ios-cli。
2. 执行基础 GraphQL 查询
现在项目已配置完成,接下来编写执行查询的代码。我们将获取国家列表及其代码和名称。
步骤 2.1:创建 GraphQL 查询
在项目文件夹中创建 Countries.graphql 文件,并添加查询:
query GetCountries { countries { code name }}之后,运行代码生成(通过 Build 或终端)。Apollo 将创建 GetCountriesQuery 和 GetCountriesQuery.Data 结构。
步骤 2.2:配置 ApolloClient
创建网络管理器:
import Apollo
class NetworkManager { static let shared = NetworkManager() private(set) lazy var apollo: ApolloClient = { let url = URL(string: "https://countries.trevorblades.com")! return ApolloClient(url: url) }()}步骤 2.3:在 SwiftUI 中执行查询
SwiftUI 示例:
import SwiftUI
struct ContentView: View { @State private var countries: [GetCountriesQuery.Data.Country] = [] var body: some View { List(countries, id: \\.code) { country in Text("\\(country.name) (\\(country.code))") } .onAppear { loadCountries() } } func loadCountries() { NetworkManager.shared.apollo.fetch(query: GetCountriesQuery()) { result in switch result { case .success(let graphQLResult): if let countries = graphQLResult.data?.countries { self.countries = countries } case .failure(let error): print("查询错误: \\(error.localizedDescription)") } } }}运行应用程序。如果一切正常,您将看到国家列表。