Getting Started

Use Supabase with iOS and SwiftUI

Learn how to create a Supabase project, add some sample data to your database, and query the data from an iOS app.


1

Create a Supabase project

Go to database.new and create a new Supabase project.

When your project is up and running, go to the Table Editor, create a new table and insert some data.

Alternatively, you can run the following snippet in your project's SQL Editor. This will create a countries table with some sample data.

SQL_EDITOR

_13
-- Create the table
_13
create table countries (
_13
id bigint primary key generated always as identity,
_13
name text not null
_13
);
_13
-- Insert some sample data into the table
_13
insert into countries (name)
_13
values
_13
('Canada'),
_13
('United States'),
_13
('Mexico');
_13
_13
alter table countries enable row level security;

Make the data in your table publicly readable by adding an RLS policy:

SQL_EDITOR

_10
create policy "public can read countries"
_10
on public.countries
_10
for select to anon
_10
using (true);

2

Create an iOS SwiftUI app with Xcode

Open Xcode > New Project > iOS > App. You can skip this step if you already have a working app.

3

Install the Supabase client library

Install Supabase package dependency using Xcode by following Apple's tutorial.

Make sure to add Supabase product package as dependency to the application.

4

Initialize the Supabase client

Create a new Supabase.swift file add a new supabase instance using your project URL and public API (anon) key:

Project URL
Anon key
Supabase.swift

_10
import Supabase
_10
_10
let supabase = SupabaseClient(
_10
supabaseURL: URL(string: "YOUR_SUPABASE_URL")!,
_10
supabaseKey: "YOUR_SUPABASE_ANON_KEY"
_10
)

5

Create a data model for countries

Create a decodable struct to deserialize the data from the database.

Add the following code to a new file named Country.swift.

Supabase.swift

_10
struct Country: Decodable, Identifiable {
_10
let id: Int
_10
let name: String
_10
}

6

Query data from the app

Use a task to fetch the data from the database and display it using a List.

Replace the default ContentView with the following code.

ContentView.swift

_22
struct ContentView: View {
_22
_22
@State var countries: [Country] = []
_22
_22
var body: some View {
_22
List(countries) { country in
_22
Text(country.name)
_22
}
_22
.overlay {
_22
if countries.isEmpty {
_22
ProgressView()
_22
}
_22
}
_22
.task {
_22
do {
_22
countries = try await supabase.from("countries").select().execute().value
_22
} catch {
_22
dump(error)
_22
}
_22
}
_22
}
_22
}

7

Start the app

Run the app on a simulator or a physical device by hitting Cmd + R on Xcode.