入门

使用 Supabase 与 iOS 和 SwiftUI

了解如何创建一个 Supabase 项目,向你的数据库添加一些示例数据,并从 iOS 应用程序查询数据。


1

创建一个 Supabase 项目

前往 database.new 并创建一个新的 Supabase 项目。

或者,您可以使用管理 API 创建项目

1
# First, get your access token from https://supabase.org.cn/dashboard/account/tokens
2
export SUPABASE_ACCESS_TOKEN="your-access-token"
3
4
# List your organizations to get the organization ID
5
curl -H "Authorization: Bearer $SUPABASE_ACCESS_TOKEN" \
6
https://api.supabase.com/v1/organizations
7
8
# Create a new project (replace <org-id> with your organization ID)
9
curl -X POST https://api.supabase.com/v1/projects \
10
-H "Authorization: Bearer $SUPABASE_ACCESS_TOKEN" \
11
-H "Content-Type: application/json" \
12
-d '{
13
"organization_id": "<org-id>",
14
"name": "My Project",
15
"region": "us-east-1",
16
"db_pass": "<your-secure-password>"
17
}'

当您的项目启动并运行时,前往 表格编辑器,创建一个新表格并插入一些数据。

或者,您可以在项目的 SQL 编辑器 中运行以下代码片段。这将创建一个包含一些示例数据的 instruments 表。

1
-- Create the table
2
create table instruments (
3
id bigint primary key generated always as identity,
4
name text not null
5
);
6
-- Insert some sample data into the table
7
insert into instruments (name)
8
values
9
('violin'),
10
('viola'),
11
('cello');
12
13
alter table instruments enable row level security;

通过添加 RLS 策略使表格中的数据可公开读取

1
create policy "public can read instruments"
2
on public.instruments
3
for select to anon
4
using (true);
2

使用 Xcode 创建 iOS SwiftUI 应用程序

打开 Xcode > 新建项目 > iOS > App。如果你已经有一个可用的应用程序,可以跳过此步骤。

3

安装 Supabase 客户端库

使用 Swift Package Manager 将 supabase-swift 包添加到你的应用程序中。

在 Xcode 中,导航到 文件 > 添加包依赖...,并在搜索栏中输入仓库 URL https://github.com/supabase/supabase-swift。有关详细说明,请参阅 Apple 的 添加包依赖教程

确保将 Supabase 产品包作为依赖项添加到你的应用程序目标。

4

初始化 Supabase 客户端

创建一个名为 Supabase.swift 的新文件,并使用你的项目 URL 和公共 API (anon) 密钥添加一个新的 Supabase 实例

项目 URL
可发布密钥
匿名密钥
Supabase.swift
1
import Supabase
2
3
let supabase = SupabaseClient(
4
supabaseURL: URL(string: "YOUR_SUPABASE_URL")!,
5
supabaseKey: "YOUR_SUPABASE_PUBLISHABLE_KEY"
6
)

你还可以从 项目的 连接 对话框 获取项目 URL 和密钥。

阅读 API 密钥文档 以全面了解所有密钥类型及其用途。

5

为乐器创建数据模型

创建一个可解码的结构体,以从数据库中反序列化数据。

将以下代码添加到名为 Instrument.swift 的新文件中。

Instrument.swift
1
struct Instrument: Decodable, Identifiable {
2
let id: Int
3
let name: String
4
}
6

从应用查询数据

使用 task 从数据库中获取数据,并使用 List 显示它。

用以下代码替换默认的 ContentView

ContentView.swift
1
import SwiftUI
2
3
struct ContentView: View {
4
5
@State var instruments: [Instrument] = []
6
7
var body: some View {
8
List(instruments) { instrument in
9
Text(instrument.name)
10
}
11
.overlay {
12
if instruments.isEmpty {
13
ProgressView()
14
}
15
}
16
.task {
17
do {
18
instruments = try await supabase.from("instruments").select().execute().value
19
} catch {
20
dump(error)
21
}
22
}
23
}
24
}
7

启动应用

通过在 Xcode 中按 Cmd + R 在模拟器或物理设备上运行该应用程序。

如果你想实现魔法链接或 OAuth 等身份验证功能,则需要设置深层链接以将用户重定向回你的应用程序。有关配置 iOS 应用程序的自定义 URL 方案的说明,请参阅 深层链接指南

下一步#

  • Swift 教程 中了解如何构建具有身份验证的完整用户管理应用程序
  • 在 GitHub 上探索 supabase-swift