• Stars
    star
    583
  • Rank 73,724 (Top 2 %)
  • Language
    Swift
  • License
    MIT License
  • Created almost 3 years ago
  • Updated 16 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Swift client for Supabase

supabase-swift

Supabase client for swift. Mirrors the design of supabase-js.

Contents


Installation

Swift Package Manager:

Add the following lines to your Package.swift file:

let package = Package(
    ...
    dependencies: [
        ...
        .package(name: "Supabase", url: "https://github.com/supabase/supabase-swift.git", branch: "master"), // Add the package
    ],
    targets: [
        .target(
            name: "YourTargetName",
            dependencies: ["Supabase"] // Add as a dependency
        )
    ]
)

If you're using Xcode, use this guide to add supabase-swift to your project. Use https://github.com/supabase/supabase-swift.git for the url when Xcode asks.

Usage

To make requests to the Supabase database, you will need to initialize a SupabaseClient object:

let client = SupabaseClient(supabaseURL: "{ Supabase URL }", supabaseKey: "{ Supabase anonymous Key }")

Login Implementation

Inside the SupabaseClient instance created before, you can find an auth property of type GoTrueClient. You can use it to perform sign in and sign up requests.

  • Here's how to sign up with an email and password and get the signed in user Session info:
Task {
  do {
      try await client.auth.signUp(email: email, password: password)
      let session = try await client.auth.session
      print("### Session Info: \(session)")
  } catch {
      print("### Sign Up Error: \(error)")
  }
}

If you wish to add metadata for the user, you can pass it as part of the data parameter, just be sure to import GoTrue first to use the User metadata values.

Task {
  do {
      try await client.auth.signUp(
        email: email,
        password: password,
        data: [
          "name": .string("John Doe"),
          "age": .number(25),
          "some_boolean_parameter": .bool(true)
        ]
      )

      let session = try await client.auth.session
      print("### Session Info: \(session)")
  } catch {
      print("### Sign Up Error: \(error)")
  }
}
  • For existing users, here's how to log in with an email and password and get the logged in user Session info:
Task {
  do {
      try await client.auth.signIn(email: email, password: password)
      let session = try await client.auth.session
      print("### Session Info: \(session)")
  } catch {
      print("### Sign Up Error: \(error)")
  }
}

Social Login Implementation

Setup Callback URL

We need to first set up the callback URL for all Social Logins inside the app.

  • Setup the callback URL on Info.plist:
<array>
    <dict>
        <key>CFBundleTypeRole</key>
        <string>Editor</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>app.yourapp://login-callback</string>
        </array>
    </dict>
</array>
  • Add this callback URL on Supabase under Authentication -> URL Configuration -> Redirect URLs.

Google Sign In

  • Setup Google Auth as per Supabase's Documentation.
  • Note: For iOS we still need to use Google Consent Form for Web.
  • Import SafariServices in your ViewController and create a SFSafariViewController instance:
import SafariServices

var safariVC: SFSafariViewController?
  • Get the URL for Google Sign in from Supabase and load it on SFSafariViewController.
  • Pass the previous callback URL you set up in the redirecTo parameter:
Task {
    do {
        let url = try await client.auth.getOAuthSignInURL(provider: Provider.google, redirectTo: URL(string: {Your Callback URL})!)
        safariVC = SFSafariViewController(url: url as URL)
        self.present(safariVC!, animated: true, completion: nil)
    } catch {
        print("### Google Sign in Error: \(error)")
    }
}
  • Handle the callback URL on SceneDelegate (for older projects, you can use AppDelegate if SceneDelegate is not present).
  • Post a NotificationCenter call to let the ViewController know the callback has been fired and pass the URL received. This URL will be used to get the user session.
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
    if let url = URLContexts.first?.url as? URL {
        if url.host == "login-callback" {
            let urlDict: [String: URL] = ["url": url]
            NotificationCenter.default.post(name: Notification.Name("OAuthCallBack"), object: nil, userInfo: urlDict)
        }
    }
}
  • In your ViewController, observe for the Notification and handle it minimizing the SFSafariViewController and getting the session:
NotificationCenter.default.addObserver(
            self,
            selector: #selector(self.oAuthCallback(_:)),
            name: NSNotification.Name(rawValue: "OAuthCallBack"),
            object: nil)

@objc func oAuthCallback(_ notification: NSNotification){
    guard let url = notification.userInfo?["url"] as? URL  else { return }
    Task {
        do {
            let session = try await SupaBaseAuth().client.session(from: url)
            print("### Session Info: \(session)")
        } catch {
            print("### oAuthCallback error: \(error)")
        }
    }
    safariVC?.dismiss(animated: true)
}

Apple Sign In

  • Setup Apple Auth as per Supabase's Documentation.
  • For Sign in with Apple follow the above as per Google Sign In and just replace the provider.
  • Once the user moves to the SFSafariViewController, an Apple native pop-up will slide up to continue with the sign in.
Task {
    do {
        let url = try await client.auth.getOAuthSignInURL(provider: **Provider.apple**, redirectTo: URL(string: {Your Callback URL})!)
        safariVC = SFSafariViewController(url: url as URL)
        self.present(safariVC!, animated: true, completion: nil)
    } catch {
        print("### Apple Sign in Error: \(error)")
    }
}

Other Social Logins

  • If using a WebViews, other social logins will be similar to above. Just follow the Supabase's Documentation for their setup.

Basic CRUD Implementation

First, import and initialize SupabaseClient, as explained in "Usage" section.

Insert Data

  • You can either use Codable or Encodable and Decodable protocols for the model's struct. However without either, you will get an error saying Cannot convert value of type 'Void' to specified type 'InsertModel' when trying to cast the response to your model.
  • Create a model which follows your table's data structure:
struct InsertModel: Encodable, Decodable {
    let id: Int? // you can choose to omit this depending on how you've setup your table
    let title: String?
    let desc: String?
}

let insertData = InsertModel(title: "Test", desc: "Test Desc")
let query = client.database
            .from("{ Your Table Name }")
            .insert(values: insertData,
                    returning: .representation) // you will need to add this to return the added data
            .select(columns: "id") // specifiy which column names to be returned. Leave it empty for all columns
            .single() // specify you want to return a single value.

Task {
    do {
        let response: [InsertModel] = try await query.execute().value
        print("### Returned: \(response)")
    } catch {
        print("### Insert Error: \(error)")
    }
}

Select Data

  • Using the same model as before:
let insertData = InsertModel(title: "Test", desc: "Test Desc")
let query = client.database
            .from("{ Your Table Name }")
            .select() // keep it empty for all, else specify returned data
            .match(query: ["title" : insertData.title, "desc": insertData.desc])
            .single()

Task {
    do {
        let response: [InsertModel] = try await query.execute().value
        print("### Returned: \(response)")
    } catch {
        print("### Select Error: \(error)")
    }
}

Update Data

  • Using the same model as before:
// Assuming the record above was inserted with id 1
let updateData = InsertModel(id: 1, title: "Test Edited", desc: "Test Desc Edited")
let query = client.database
            .from("{ Your Table Name }")
            .update(values: updateData,
                    returning: .representation) // you will need to add this to return the updated data
            .select(columns: "id") // specifiy which column names to be returned. Leave it empty for all columns
            .single() // specify you want to return a single value.

Task {
    do {
        let response: [InsertModel] = try await query.execute().value
        print("### Returned: \(response)")
    } catch {
        print("### Update Error: \(error)")
    }
}

Delete Data

let query = client.database
            .from("{ Your Table Name }")
            .delete(returning: .representation) // you will need to add this to return the deleted data
            .match(
                query: ["id" : 1] // assuming the record above was inserted with id 1
                // You can add additional conditions here
            )
            .select() // specifiy which column names to be returned. Leave it empty for all columns
            .single()

Task {
    do {
        let response: [InsertModel] = try await query.execute().value
        print("### Returned: \(response)")
    } catch {
        print("### Delete Error: \(error)")
    }
}

Postgres Functions

  • Unlike the JavaScript library, you can't use the rpc method on the SupabaseClient, instead you need to use the rpc method on the PostgresClient:
struct YourFunctionNameParams: Codable {
    let param1: String
    let param2: String
}

let query = client.database.rpc(
    fn: "your_function_name",
    params: YourFunctionNameParams(param1: "param1", param2: "param2")
)
// Like in Supabase-js, you can use the `.single` method to return a single value.

Task {
    do {
        let response: [DataModel] = try await query.execute().value // Where DataModel is the model of the data returned by the function
        print("### Returned: \(response)")
    } catch {
        print("### RPC Error: \(error)")
    }
}

Contributing

  • Fork the repo on GitHub
  • Clone the project to your own machine
  • Commit changes to your own branch
  • Push your work back up to your fork
  • Submit a Pull request so that we can review your changes and merge

Sponsors

We are building the features of Firebase using enterprise-grade, open source products. We support existing communities wherever possible, and if the products don’t exist we build them and open source them ourselves. Thanks to these sponsors who are making the OSS ecosystem better for everyone.

New Sponsor

More Repositories

1

supabase

The open source Firebase alternative.
TypeScript
65,693
star
2

realtime

Broadcast, Presence, and Postgres Changes via WebSockets
Elixir
6,458
star
3

postgres_lsp

A Language Server for Postgres
Rust
3,073
star
4

supabase-js

An isomorphic Javascript client for Supabase. Query your Supabase database, subscribe to realtime events, upload and download files, browse typescript examples, invoke postgres functions via rpc, invoke supabase edge functions, query pgvector.
TypeScript
2,822
star
5

pg_graphql

GraphQL support for PostgreSQL
Rust
2,760
star
6

supavisor

A cloud-native, multi-tenant Postgres connection pooler.
Elixir
1,574
star
7

ui

Supabase UI Library
TypeScript
1,510
star
8

postgres

Unmodified Postgres with some useful plugins
Shell
1,265
star
9

index_advisor

PostgreSQL Index Advisor
PLpgSQL
1,263
star
10

auth

A JWT based API for managing users and issuing JWT tokens
Go
1,159
star
11

pg_jsonschema

PostgreSQL extension providing JSON Schema validation
Rust
929
star
12

postgrest-js

Isomorphic JavaScript client for PostgREST.
TypeScript
917
star
13

auth-helpers

A collection of framework specific Auth utilities for working with Supabase.
TypeScript
877
star
14

cli

Supabase CLI. Manage postgres migrations, run Supabase locally, deploy edge functions. Postgres backups. Generating types from your database schema.
Go
849
star
15

postgres-meta

A RESTful API for managing your Postgres. Fetch tables, add roles, and run queries
TypeScript
820
star
16

storage

S3 compatible object storage service that stores metadata in Postgres
TypeScript
640
star
17

supabase-flutter

Flutter integration for Supabase. This package makes it simple for developers to build secure and scalable products.
Dart
613
star
18

supa_audit

Generic Table Auditing
PLpgSQL
611
star
19

edge-runtime

A server based on Deno runtime, capable of running JavaScript, TypeScript, and WASM services.
Rust
557
star
20

stripe-sync-engine

Sync your Stripe account to you Postgres database.
TypeScript
457
star
21

wrappers

Postgres Foreign Data Wrapper development framework in Rust.
Rust
433
star
22

auth-ui

Pre-built Auth UI for React
TypeScript
405
star
23

supabase-dart

A Dart client for Supabase
Dart
402
star
24

pg_crdt

POC CRDT support in Postgres
Rust
372
star
25

dbdev

Database Package Registry for Postgres
PLpgSQL
329
star
26

auth-js

An isomorphic Javascript library for Supabase Auth.
CSS
298
star
27

realtime-js

An isomorphic Javascript client for Supabase Realtime server.
JavaScript
288
star
28

examples-archive

Supabase Examples Archive
TypeScript
278
star
29

pg_netstat

PostgreSQL extension to monitor database network traffic
Rust
246
star
30

grid

A react component to display your Postgresql table data. Used in Supabase Dashboard app.
TypeScript
197
star
31

vecs

Postgres/pgvector Python Client
Python
190
star
32

libcluster_postgres

Postgres strategy for libcluster
Elixir
178
star
33

pg_net

A PostgreSQL extension that enables asynchronous (non-blocking) HTTP/HTTPS requests with SQL
PLpgSQL
165
star
34

vault

Extension for storing encrypted secrets in the Vault
PLpgSQL
161
star
35

postgrest-dart

Dart client for PostgREST
Dart
137
star
36

headless-vector-search

Supabase Toolkit to perform vector similarity search on your knowledge base embeddings.
TypeScript
135
star
37

workflows

Elixir
133
star
38

supabase-grafana

Observability for your Supabase project, using Prometheus/Grafana
Shell
132
star
39

walrus

Applying RLS to PostgreSQL WAL
PLpgSQL
117
star
40

storage-js

JS Client library to interact with Supabase Storage
TypeScript
111
star
41

postgres-deno

A PostgreSQL extension for Deno: run Typescript in PostgreSQL functions and triggers.
104
star
42

realtime-dart

A dart client for Supabase Realtime server.
Dart
85
star
43

setup-cli

A GitHub action for interacting with your Supabase projects using the CLI.
TypeScript
83
star
44

repository.surf

🏄
JavaScript
80
star
45

embeddings-generator

GitHub Action to generate embeddings from the markdown files in your repository.
TypeScript
79
star
46

supabase-ui-web

TypeScript
74
star
47

self-hosted-edge-functions-demo

A demo of how to self-host Supabase Edge Functions on Fly.io
TypeScript
61
star
48

functions-js

TypeScript
54
star
49

supabase-admin-api

API to administer the Supabase server (KPS)
Go
51
star
50

supautils

PostgreSQL extension that secures a cluster on a cloud environment
C
49
star
51

gotrue-dart

A dart client library for GoTrue.
Dart
47
star
52

supabase-action-example

TypeScript
45
star
53

benchmarks

SCSS
41
star
54

grafana-agent-fly-example

Deploy a Grafana Agent on Fly to scrape Prometheus metrics from Supabase and send them to Grafana Cloud
Shell
36
star
55

functions-relay

API Gateway for Supabase Edge functions
TypeScript
35
star
56

nix-postgres

Experimental port of supabase/postgres to Nix
Nix
35
star
57

benchmarks-archive

Infrastucture benchmarks
Nix
31
star
58

hibp

Go library for HaveIBeenPwned.org's pwned passwords API.
Go
29
star
59

splinter

Supabase Postgres Linter
PLpgSQL
28
star
60

supabase.ai

iykyk
HTML
27
star
61

storage-dart

Dart client library to interact with Supabase Storage
Dart
22
star
62

livebooks

A collection of Elixir Livebooks for Supabase
Dockerfile
20
star
63

base64url-js

Pure TypeScript implementation of Base64-URL encoding for JavaScript strings.
TypeScript
19
star
64

terraform-provider-supabase

Go
17
star
65

orb-sync-engine

TypeScript
12
star
66

.github

Org-wide default community health files & templates.
11
star
67

auth-elements

Components to add Supabase Auth to any application
TypeScript
11
star
68

rfcs

11
star
69

functions-dart

Dart
8
star
70

test-reports

Repository to store test reports data and host reporting in gh-pages
7
star
71

plug_caisson

An Elixir Plug library for handling compressed requests
Elixir
6
star
72

flyswatter

Deploy a global pinger on Fly
Elixir
6
star
73

scoop-bucket

4
star
74

tests

TypeScript
4
star
75

pgextkit

Rust
3
star
76

homebrew-tap

Ruby
3
star
77

fly-preview

TypeScript
3
star
78

shared-types

TypeScript
3
star
79

supa_type

The Missing PostgreSQL Data Types
Nix
3
star
80

test-inspector

Check your test results against the reference run and compare coverage for multiple client libraries
Go
2
star
81

mailme

A clone of Netlify's mailme package used in Supabase Auth / GoTrue.
Go
2
star
82

productions

Supabase SynthWave. The best soundtrack to build an app in a weekend and scale to billions.
TypeScript
1
star
83

design-tokens

1
star