Prepare for the PgBouncer and IPv4 deprecations on 26th January 2024

Swift Reference v2.0

Swift Client Library

@supabase-community/supabase-swift

This reference documents every object and method available in Supabase's Swift library, supabase-swift. You can use supabase-swift to interact with your Postgres database, listen to database changes, invoke Deno Edge Functions, build login and user management functionality, and manage large files.

We also provide a supabase package for non-Swift projects.

The Swift client library is created and maintained by the Supabase community, and is not an official library. Please be tolerant of areas where the library is still being developed, and — as with all the libraries — feel free to contribute wherever you find issues.

Huge thanks to official maintainers, Guilherme and Maail.

Initializing

You can initialize Supabase with the SupabaseClient by passing your Project URL and Project Key. You can find these under your Project SettingsAPI Settings The Supabase client is your entrypoint to the rest of the Supabase functionality and is the easiest way to interact with everything we offer within the Supabase ecosystem.


let client = SupabaseClient(supabaseURL: URL(string: "https://xyzcompany.supabase.co")!, supabaseKey: "public-anon-key")

Fetch data

  • By default, Supabase projects will return a maximum of 1,000 rows. This setting can be changed in Project API Settings. It's recommended that you keep it low to limit the payload size of accidental or malicious requests. You can use range() queries to paginate through your data.
  • select() can be combined with Modifiers
  • select() can be combined with Filters
  • If using the Supabase hosted platform apikey is technically a reserved keyword, since the API gateway will pluck it out for authentication. It should be avoided as a column name.
  • The recommended solution for getting data is to use the value property which will return a decoded model. Create a Codable to easily decode your database responses.

struct Country: Decodable {
  let id: Int
  let name: String
}

let countries: [Country] = try await supabase.database
  .from("countries")
  .select()
  .execute()
  .value

Insert data


struct Country: Encodable {
  let id: Int
  let name: String
}

let country = Country(id: 1, name: "Denmark")

try await supabase.database
  .from("countries")
  .insert(country)
  .execute()

Update data

  • update() should always be combined with Filters to target the item(s) you wish to update.

try await supabase.database
  .from("countries")
  .update(["name": "Australia"])
  .eq("id", value: 1)
  .execute()

Upsert data

  • Primary keys must be included in values to use upsert.

struct Country: Encodable {
  let id: Int
  let name: String
}
try await supabase.database
  .from("countries")
  .upsert(Country(id: 1, name: "Albania"))
  .execute()

Delete data

  • delete() should always be combined with filters to target the item(s) you wish to delete.
  • If you use delete() with filters and you have RLS enabled, only rows visible through SELECT policies are deleted. Note that by default no rows are visible, so you need at least one SELECT/ALL policy that makes the rows visible.

try await supabase.database
  .from("countries")
  .delete()
  .eq("id", value: 1)
  .execute()

Call a Postgres function

You can call Postgres functions as Remote Procedure Calls, logic in your database that you can execute from anywhere. Functions are useful when the logic rarely changes—like for password resets and updates.

create or replace function hello_world() returns text as $$
  select 'Hello world';
$$ language sql;

let value: String = try await supabase.database
  .rpc("hello_world")
  .execute()
  .value

Using filters

Filters allow you to only return rows that match certain conditions.

Filters can be used on select(), update(), upsert(), and delete() queries.

If a Postgres function returns a table response, you can also apply filters.

Implement URLQueryRepresentable protocol in your own types to be able to use them as filter value.

Supported filtes are: eq, neq, gt, gte, lt, lte, like, ilike, is, in, cs, cd, sl, sr, nxl, nxr, adj, ov, fts, plfts, phfts, wfts. Check available operators in PostgREST.


try await supabase.database
  .from("cities")
  .select("name, country_id")
  .eq("name", value: "The Shire")    // Correct

try await supabase.database
  .from("citites")
  .eq("name", value: "The Shire")    // Incorrect
  .select("name, country_id")

Match an associated value


try await supabase.database
  .from("countries")
  .select("name")
  .match(["id": 2, "name": "Albania"])

Don't match the filter

Finds all rows that don't satisfy the filter.

  • .not() expects you to use the raw PostgREST syntax for the filter names and values.

    1.not("name", operator: .eq, value: "Paris")
    2.not("arraycol", operator: .cs, value: #"{"a","b"}"#) // Use Postgres array {} for array column and 'cs' for contains.
    3.not("rangecol", operator: .cs, value: "(1,2]") // Use Postgres range syntax for range column.
    4.not("id", operator: .in, value: "(6,7)")  // Use Postgres list () and 'in' for in_ filter.
    5.not("id", operator: .in, value: "(\(mylist.join(separator: ",")))")  // You can insert a Swift list array.

try await supabase.database
  .from("countries")
  .select()
  .not("name", operator: .is, value: "")
  .execute()

Match at least one filter

or() expects you to use the raw PostgREST syntax for the filter names and values.

1.or(#"id.in.(5,6,7), arraycol.cs.{"a","b"}"#)  // Use `()` for `in` filter, `{}` for array values and `cs` for `contains()`.
2.or(#"id.in.(5,6,7), arraycol.cd.{"a","b"}"#)  // Use `cd` for `containedBy()`

try await supabase.database
  .from("countries")
  .select("name")
  .or("id.eq.2,name.eq.Algeria")

Match the filter

filter() expects you to use the raw PostgREST syntax for the filter values.

1.filter("id", operator: .in, value: "(5,6,7)")  // Use `()` for `in` filter
2.filter("arraycol", operator: .cs, value: #"{"a","b"}"#)  // Use `cs` for `contains()`, `{}` for array values

try await supabase.database
  .from("countries")
  .select()
  .filter("name", operator: .in, value: #"("Algeria","Japan")"#)

Using modifiers

Filters work on the row level—they allow you to return rows that only match certain conditions without changing the shape of the rows. Modifiers are everything that don't fit that definition—allowing you to change the format of the response (e.g. returning a CSV string).

Modifiers must be specified after filters. Some modifiers only apply for queries that return rows (e.g., select() or rpc() on a function that returns a table response).

Return data after inserting

Perform a SELECT on the query result.


  try await database.database
    .from("countries")
    .upsert(CountryModel(id: 1, name: "Algeria"))
    .select()
    .execute()

Order the results

Order the query result by column.


try await supabase.database
  .from("countries")
  .select("id, name")
  .order("id", ascending: false)
  .execute()

Limit the number of rows returned

Limit the query result by count.


try await supabase.database
  .from("countries")
  .select("id, name")
  .limit(1)
  .execute()

Limit the query to a range

Limit the query result by from and to inclusively.


try await supabase.database
  .from("countries")
  .select(
    """
      name,
      cities (
        name
      )
    """
  )
  .range(from: 0, to: 1)
  .execute()

Retrieve one row of data

By default PostgREST returns all JSON results in an array, even when there is only one item, use single() to return the first object unenclosed by an array.


try await supabase.database
  .from("countries")
  .select("name")
  .limit(1)
  .single()
  .execute()

Retrieve as a CSV


try await supabase
  .from("countries")
  .select()
  .csv()
  .execute()

Overview

  • The auth methods can be accessed via the supabase.auth namespace.

let supabase = SupabaseClient(supabaseURL: URL(string: "https://xyzcompany.supabase.co")!, supabaseKey: "public-anon-key")
let auth = supabase.auth

Create a new user

  • By default, the user needs to verify their email address before logging in. To turn this off, disable Confirm email in your project.
  • Confirm email determines if users need to confirm their email address after signing up.
    • If Confirm email is enabled, a user is returned but session is null.
    • If Confirm email is disabled, both a user and a session are returned.
  • When the user confirms their email address, they are redirected to the SITE_URL by default. You can modify your SITE_URL or add additional redirect URLs in your project.
  • If signUp() is called for an existing confirmed user:
    • When both Confirm email and Confirm phone (even when phone provider is disabled) are enabled in your project, an obfuscated/fake user object is returned.
    • When either Confirm email or Confirm phone (even when phone provider is disabled) is disabled, the error message, User already registered is returned.
  • To fetch the currently logged-in user, refer to getUser().

try await supabase.auth.signUp(
  email: "example@email.com",
  password: "example-password"
)

Listen to auth events

  • Types of auth events: INITIAL_SESSION, SIGNED_IN, SIGNED_OUT, TOKEN_REFRESHED, USER_UPDATED, PASSWORD_RECOVERY, MFA_CHALLENGE_VERIFIED
  • The INITIAL_SESSION can be used to allow you to invoke the callback function when authStateChanges is first called.

for await (event, session) in await supabase.auth.authStateChanges {
  print(event, session)
}

Sign in a user

  • Requires either an email and password or a phone number and password.

try await supabase.auth.signIn(
  email: "example@email.com",
  password: "example-password"
)

Sign in with ID Token


let session = try await supabase.auth.signInWithIdToken(
  credentials: OpenIDConnectCredentials(
    provider: .apple,
    idToken: "your-id-token",
    nonce: "your nonce"
  )
)

Sign in a user through OTP

  • This method is used for passwordless sign-ins where a OTP is sent to the user's email or phone number.
  • If the user doesn't exist, signInWithOTP() will signup the user instead. To restrict this behavior, you can set shouldCreateUser to false.
  • If you're using an email, you can configure whether you want the user to receive a magiclink or a OTP.
  • If you're using phone, you can configure whether you want the user to receive a OTP.
  • The magic link's destination URL is determined by the SITE_URL.
  • See redirect URLs and wildcards to add additional redirect URLs to your project.
  • Magic links and OTPs share the same implementation. To send users a one-time code instead of a magic link, modify the magic link email template to include {{ .Token }} instead of {{ .ConfirmationURL }}.
  • When using magic links, specify a redirectTo that matches a configured url scheme in your iOS app, so Supabase can correctly redirect back to your app.
  • See our Twilio Phone Auth Guide for details about configuring WhatsApp sign in.

try await supabase.auth.signInWithOTP(
  email: "example@email.com",
  redirectTo: URL(string: "my-app-scheme://")!
)

Sign in a user through OAuth

  • This method is used for signing in using a third-party provider.
  • Supabase supports many different third-party providers.

let url = try await supabase.auth.getOAuthSignInURL(provider: .github)

let session = ASWebAuthenticationSession(url: url, callbackURLScheme: "my-app-scheme") { url, error in 
  guard let url else { return }

  Task {
    try await supabase.auth.session(from: url)
  }
}

session.presentationContextProvider = self // yours ASWebAuthenticationPresentationContextProviding implementation.

session.start()

Sign out a user

  • In order to use the signOut() method, the user needs to be signed in first.

try await supabase.auth.signOut()

Verify and log in through OTP

  • The verifyOTP method takes in different verification types. If a phone number is used, the type can either be sms or phone_change. If an email address is used, the type can be one of the following: signup, magiclink, recovery, invite, email_change, or email.
  • The verification type used should be determined based on the corresponding auth method called before verifyOTP to sign up / sign-in a user.

try await supabase.auth.verifyOTP(
  phone: "+13334445555",
  token: "123456",
  type: .sms
)

Retrieve a session

  • Returns the session, refreshing it if necessary. If no session can be found, a GoTrueError.sessionNotFound error is thrown.

try await supabase.auth.session

Retrieve a new session

  • This method will refresh the session whether the current one is expired or not.

let session = try await supabase.auth.refreshSession()

Retrieve a user

  • This method is useful for checking if the user is authorized because it validates the user's access token JWT on the server.
  • Fetches the user object from the database instead of local session.
  • Should be used only when you require the most current user data. For faster results, session.user is recommended.

let user = try await supabase.auth.user()

Update a user

  • In order to use the updateUser() method, the user needs to be signed in first.
  • By default, email updates sends a confirmation link to both the user's current and new email. To only send a confirmation link to the user's new email, disable Secure email change in your project's email auth provider settings.

try await supabase.auth.update(user: UserAttributes(email: "new@email.com"))

Resend an OTP

  • Resends a signup confirmation, email change, or phone change email to the user.
  • Passwordless sign-ins can be resent by calling the signInWithOTP() method again.
  • Password recovery emails can be resent by calling the resetPasswordForEmail() method again.
  • This method only resends an email or phone OTP to the user if there an initial signup, email change, or phone change request was made.
  • You can specify a redirect URL when you resend an email link using the emailRedirectTo option.

try await supabase.auth.resend(
  email: "email@example.com",
  type: .signup,
  emailRedirectTo: URL(string: "my-app-scheme://")
)

Set the session data

  • setSession() takes in a refresh token and uses it to get a new session.
  • The refresh token can only be used once to obtain a new session.
  • Refresh token rotation is enabled by default on all projects to guard against replay attacks.
  • You can configure the REFRESH_TOKEN_REUSE_INTERVAL which provides a short window in which the same refresh token can be used multiple times in the event of concurrency or offline issues.

  try await supabase.auth.setSession(accessToken: "access_token", refreshToken: "refresh_token")

Exchange an auth code for a session

  • Used when flowType is set to pkce in client options.

try await supabase.auth.exchangeCodeForSession(authCode: "34e770dd-9ff9-416c-87fa-43b31d7ef225")

Auth MFA

This section contains methods commonly used for Multi-Factor Authentication (MFA) and are invoked behind the supabase.auth.mfa namespace.

Currently, we only support time-based one-time password (TOTP) as the 2nd factor. We don't support recovery codes but we allow users to enroll more than 1 TOTP factor, with an upper limit of 10.

Having a 2nd TOTP factor for recovery frees the user of the burden of having to store their recovery codes somewhere. It also reduces the attack surface since multiple recovery codes are usually generated compared to just having 1 backup TOTP factor.

Enroll a factor

  • Currently, totp is the only supported factorType. The returned id should be used to create a challenge.
  • To create a challenge, see mfa.challenge().
  • To verify a challenge, see mfa.verify().
  • To create and verify a challenge in a single step, see mfa.challengeAndVerify().

let response = try await supabase.auth.mfa.enroll(
  params: MFAEnrollParams(
    issuer: "optional issuer",
    friendlyName: "optional friendly name"
  )
)

// Use the id to create a challenge.
// The challenge can be verified by entering the code generated from the authenticator app.
// The code will be generated upon scanning the qrCode or entering the secret into the authenticator app.
let id = response.id
let type = response.type
let qrCode = response.totp?.qrCode
let secret = response.totp?.secret
let uri = response.totp?.uri

Create a challenge


let response = try await supabase.auth.mfa.challenge(
  params: MFAChallengeParams(
    factorId: "34e770dd-9ff9-416c-87fa-43b31d7ef225"
  )
)

Verify a challenge


let session = try await supabase.auth.mfa.verify(
  params: MFAVerifyParams(
    factorId: "34e770dd-9ff9-416c-87fa-43b31d7ef225",
    challengeId: "4034ae6f-a8ce-4fb5-8ee5-69a5863a7c15",
    code: "123456"
  )
)

Create and verify a challenge


let session = try await supabase.auth.mfa.challengeAndVerify(
  params: MFAChallengeAndVerifyParams(
    factorId: "34e770dd-9ff9-416c-87fa-43b31d7ef225",
    code: "123456"
  )
)

Unenroll a factor


let response = try await supabase.auth.mfa.unenroll(
  params: MFAUnenrollParams(
    factorId: "34e770dd-9ff9-416c-87fa-43b31d7ef225"
  )
)

Get Authenticator Assurance Level

  • Authenticator Assurance Level (AAL) is the measure of the strength of an authentication mechanism.
  • In Supabase, having an AAL of aal1 refers to having the 1st factor of authentication such as an email and password or OAuth sign-in while aal2 refers to the 2nd factor of authentication such as a time-based, one-time-password (TOTP).
  • If the user has a verified factor, the nextLevel field will return aal2, else, it will return aal1.

let aal = try await supabase.auth.mfa.getAuthenticatorAssuranceLevel()
let currentLevel = aal.currentLevel
let nextLevel = aal.nextLevel
let currentAuthenticationMethods = aal.currentAuthenticationMethods

List all factors for a user


let factors = try await supabase.auth.mfa.listFactors()

Invokes a Supabase Edge Function.

Invoke a Supabase Edge Function.

  • Requires an Authorization header.
  • When you pass in a body to your function, we automatically attach the Content-Type header for String, and Data. If it doesn't match any of these types we assume the payload is json, serialize it and attach the Content-Type header as application/json. You can override this behaviour by passing in a Content-Type header of your own.

struct Response: Decodable {
  // Expected response definition
}

let response: Response = try await supabase.functions
  .invoke(
    "hello", 
    options: FunctionInvokeOptions(
      body: ["foo": "bar"]
    )
  )

Subscribe to channel

  • By default, Broadcast and Presence are enabled for all projects.
  • By default, listening to database changes is disabled for new projects due to database performance and security concerns. You can turn it on by managing Realtime's replication.
  • You can receive the "previous" data for updates and deletes by setting the table's REPLICA IDENTITY to FULL (e.g., ALTER TABLE your_table REPLICA IDENTITY FULL;).
  • Row level security is not applied to delete statements. When RLS is enabled and replica identity is set to full, only the primary key is sent to clients.

let channel = supabase
  .realtime
  .channel("room1")

channel
  .on("broadcast", filter: ChannelFilter(event: "cursor-pos")) { message in 
    print("Cursor position received!", message.payload)
  }
  .subscribe { status, error in
    if status == .subscribed {
      Task {
        await channel.send(
          type: .broadcast,
          event: "cursor-pos",
          payload: ["x": Double.random(in: 0...1), "y": Double.random(in: 0...1)]
        )
      }
    }
  }

Unsubscribe from a channel

  • Removing a channel is a great way to maintain the performance of your project's Realtime service as well as your database if you're listening to Postgres changes. Supabase will automatically handle cleanup 30 seconds after a client is disconnected, but unused channels may cause degradation as more clients are simultaneously subscribed.

supabase.realtime.remove(myChannel)

Unsubscribe from all channels

  • Removing channels is a great way to maintain the performance of your project's Realtime service as well as your database if you're listening to Postgres changes. Supabase will automatically handle cleanup 30 seconds after a client is disconnected, but unused channels may cause degradation as more clients are simultaneously subscribed.

supabase.realtime.removeAllChannels()

Retrieve all channels


let channels = supabase.realtime.channels

Broadcast a message

Broadcast a message to all connected clients to a channel.

  • When using REST you don't need to subscribe to the channel

supabase.realtime
  .channel("room1")
  .subscribe { status, error in
    if status == .subscribed {
      Task {
        await channel.send(
          type: "broadcast",
          event: "cursor-pos",
          payload: ["x": Double.random(in: 0...1), "y": Double.random(in: 0...1)]
        )
      }
    }
  }

Create a bucket

  • RLS policy permissions required:
    • buckets table permissions: insert
    • objects table permissions: none
  • Refer to the Storage guide on how access control works

try await supabase.storage
  .createBucket(
    "avatars", 
    options: BucketOptions(
      public: false,
      allowedMimeTypes: ["image/png"],
      fileSizeLimit: 1024
    )
  )

Retrieve a bucket

  • RLS policy permissions required:
    • buckets table permissions: select
    • objects table permissions: none
  • Refer to the Storage guide on how access control works

let bucket = try await supabase.storage
  .getBucket("avatars")

List all buckets

  • RLS policy permissions required:
    • buckets table permissions: select
    • objects table permissions: none
  • Refer to the Storage guide on how access control works

try await supabase.storage
  .listBuckets()

Update a bucket

  • RLS policy permissions required:
    • buckets table permissions: select and update
    • objects table permissions: none
  • Refer to the Storage guide on how access control works

try await supabase.storage
  .updateBucket(
    "avatars", 
    options: BucketOptions(
      public: false,
      fileSizeLimit: 1024,
      allowedMimeTypes: ["image/png"]
    )
  )

Delete a bucket

  • RLS policy permissions required:
    • buckets table permissions: select and delete
    • objects table permissions: none
  • Refer to the Storage guide on how access control works

try await supabase.storage
  .deleteBucket("avatars")

Empty a bucket

  • RLS policy permissions required:
    • buckets table permissions: select
    • objects table permissions: select and delete
  • Refer to the Storage guide on how access control works

try await supabase.storage
  .emptyBucket("avatars")

Upload a file

  • RLS policy permissions required:
    • buckets table permissions: none
    • objects table permissions: only insert when you are uploading new files and select, insert and update when you are upserting files
  • Refer to the Storage guide on how access control works

let fileName = "avatar1.png"

try await supabase.storage
  .from("avatars")
  .upload(
    path: "public/\(fileName)",
    file: fileData,
    fileOptions: FileOptions(
      cacheControl: "3600",
      upsert: false
    )
  )

Download a file

  • RLS policy permissions required:
    • buckets table permissions: none
    • objects table permissions: select
  • Refer to the Storage guide on how access control works

let data = try await supabase.storage
  .from("avatars")
  .download(path: "folder/avatar1.png")

List all files in a bucket

  • RLS policy permissions required:
    • buckets table permissions: none
    • objects table permissions: select
  • Refer to the Storage guide on how access control works

let files = try await supabase.storage
  .from("avatars")
  .list(
    path: "folder",
    options: SearchOptions(
      limit: 100,
      offset: 0,
      sortBy: SortBy(column: "name", order: "asc")
    )
  )

Replace an existing file

  • RLS policy permissions required:
    • buckets table permissions: none
    • objects table permissions: update and select
  • Refer to the Storage guide on how access control works

let fileName = "avatar1.png"

try await supabase.storage
  .from("avatars")
  .update(
    path: "public/\(fileName)",
    file: fileData,
    fileOptions: FileOptions(
      cacheControl: "3600",
      upsert: true
    )
  )

Move an existing file

  • RLS policy permissions required:
    • buckets table permissions: none
    • objects table permissions: update and select
  • Refer to the Storage guide on how access control works

try await supabase
  .storage
  .from("avatars")
  .move(from: "public/avatar1.png", to: "private/avatar2.png")

Copy an existing file

  • RLS policy permissions required:
    • buckets table permissions: none
    • objects table permissions: insert and select
  • Refer to the Storage guide on how access control works

try await supabase
  .storage
  .from("avatars")
  .copy(from: "public/avatar1.png", to: "private/avatar2.png")

Delete files in a bucket

  • RLS policy permissions required:
    • buckets table permissions: none
    • objects table permissions: delete and select
  • Refer to the Storage guide on how access control works

try await supabase.storage
  .from("avatars")
  .remove(paths: ["folder/avatar1.png"])

Create a signed URL

  • RLS policy permissions required:
    • buckets table permissions: none
    • objects table permissions: select
  • Refer to the Storage guide on how access control works

let signedURL = try await supabase.storage
  .from("avatars")
  .createSignedURL(path: "folder/avatar1.png", expiresIn: 60)

Retrieve public URL

  • The bucket needs to be set to public, either via updateBucket() or by going to Storage on supabase.com/dashboard, clicking the overflow menu on a bucket and choosing "Make public"
  • RLS policy permissions required:
    • buckets table permissions: none
    • objects table permissions: none
  • Refer to the Storage guide on how access control works

let publicURL = try supabase.storage
  .from("public-bucket")
  .getPublicURL(path: "folder/avatar1.png")