출처: https://supabase.com/docs/guides/getting-started/quickstarts/ios-swiftui
Supabase와 iOS(SwiftUI)를 함께 사용하는 방법을 알아봅니다. Supabase 프로젝트를 생성하고, 데이터베이스에 샘플 데이터를 추가한 뒤, iOS 앱에서 데이터를 쿼리하는 방법을 안내합니다.
1. Supabase 프로젝트 생성하기
database.new에 접속하여 새로운 Supabase 프로젝트를 생성하세요.
프로젝트가 준비되면 Table Editor로 이동하여 새 테이블을 만들고 데이터를 삽입합니다.
또는, 아래 SQL 스니펫을 프로젝트의 SQL Editor에서 실행할 수 있습니다. 이 코드는 instruments
테이블을 생성하고 샘플 데이터를 추가합니다.
-- 테이블 생성
create table instruments (
id bigint primary key generated always as identity,
name text not null
);
-- 샘플 데이터 삽입
insert into instruments (name)
values ('violin'),
('viola'),
('cello');
alter table instruments enable row level security;
테이블 데이터를 공개적으로 읽을 수 있도록 RLS 정책 추가
create policy "public can read instruments"
on public.instruments
for select to anon
using (true);
2. iOS SwiftUI 앱 생성하기
Xcode > New Project > iOS > App을 선택하여 새 프로젝트를 생성하세요. 이미 앱이 있다면 이 단계는 건너뛰어도 됩니다.
3. Supabase 클라이언트 라이브러리 설치하기
Xcode에서 Apple의 튜토리얼을 참고하여 Supabase 패키지 의존성을 추가하세요.
- 반드시
Supabase
product 패키지를 앱의 의존성에 추가해야 합니다.
4. Supabase 클라이언트 초기화하기
Supabase.swift
파일을 새로 만들고, 아래와 같이 Supabase 인스턴스를 생성하세요. (프로젝트 URL과 public API(anon) 키를 입력해야 합니다)
import Supabase
let supabase = SupabaseClient(
supabaseURL: URL(string: "YOUR_SUPABASE_URL")!,
supabaseKey: "YOUR_SUPABASE_ANON_KEY"
)
5. 악기 데이터 모델 생성하기
데이터베이스에서 받아온 데이터를 디코딩할 수 있도록 Decodable 구조체를 만드세요. Instrument.swift
라는 새 파일에 아래 코드를 추가합니다.
struct Instrument: Decodable, Identifiable {
let id: Int
let name: String
}
6. 앱에서 데이터 쿼리하기
task
를 사용해 데이터베이스에서 데이터를 가져오고, List
로 결과를 표시하세요. 기본 ContentView
를 아래 코드로 교체하세요.
struct ContentView: View {
@State var instruments: [Instrument] = []
var body: some View {
List(instruments) { instrument in
Text(instrument.name)
}
.overlay {
if instruments.isEmpty {
ProgressView()
}
}
.task {
do {
instruments = try await supabase.from("instruments").select().execute().value
} catch {
dump(error)
}
}
}
}
7. 앱 실행하기
Xcode에서 시뮬레이터 또는 실제 기기에서 Cmd + R
을 눌러 앱을 실행하세요.
출처: https://supabase.com/docs/guides/getting-started/quickstarts/ios-swiftui