Supabase Swift SDK

repository·main·Indexed 22 days ago

https://github.com/supabase/supabase-swift

A comprehensive client library for integrating Supabase services—including Auth, Database (PostgREST), Realtime, Storage, and Edge Functions—into Swift-based applications. The SDK supports full client installation or individual library imports via Swift Package Manager, and includes features such as OpenTelemetry trace propagation and support for various OAuth providers.

Tokens
5.9K
Snippets
20
Records
29
Agent score
79%

What's inside supabase-swift

  1. Supabase Swift SDK requirements and platform support

    main

    Minimum Requirements

    • iOS: 16.0+
    • macOS: 13.0+
    • tvOS: 16+
    • watchOS: 9+
    • visionOS: 1+
    • Xcode: 16.4+
    • Swift: 6.1+

    Support Policy

    • Xcode & Swift: Support is maintained for versions currently eligible for App Store submission. Dropping support for older versions is considered a minor release and not a breaking change.
    • Platforms: Support is maintained for the four latest major versions of each platform. For macOS, yearly releases are treated as major versions.
    • Unofficial Support: Android, Linux, and Windows work but are not officially supported and may stop working in future versions.
  2. Manage async operation states with ActionState

    main

    The examples use a consistent ActionState enum to manage the lifecycle of asynchronous operations (like API calls) in the UI. This helps in handling loading, success, and error states predictably.

    enum ActionState<Success, Failure: Error> {
      case idle
      case inFlight
      case result(Result<Success, Failure>)
    }
  3. Set up the Database Schema for User Management

    main

    To build a user management system, you need a profiles table that links to Supabase Auth users via a UUID. You must also enable Row Level Security (RLS) and define policies to control who can view, insert, or update profiles. Additionally, you should set up a storage bucket for user avatars and configure RLS for storage objects to allow public access and uploads.

    -- Create a table for public "profiles"
    create table profiles (
      id uuid references auth.users not null,
      updated_at timestamp with time zone,
      username text unique,
      avatar_url text,
      website text,
    
      primary key (id),
      unique(username),
      constraint username_length check (char_length(username) >= 3)
    );
    
    alter table profiles enable row level security;
    
    create policy "Public profiles are viewable by everyone."
      on profiles for select
      using ( true );
    
    create policy "Users can insert their own profile."
      on profiles for insert
      with check ( auth.uid() = id );
    
    create policy "Users can update own profile."
      on profiles for update
      using ( auth.uid() = id );
    
    -- Set up Realtime!
    begin;
      drop publication if exists supabase_realtime;
      create publication supabase_realtime;
    commit;
    alter publication supabase_realtime add table profiles;
    
    -- Set up Storage!
    insert into storage.buckets (id, name)
    values ('avatars', 'avatars');
    
    create policy "Avatar images are publicly accessible."
      on storage.objects for select
      using ( bucket_id = 'avatars' );
    
    create policy "Anyone can upload an avatar."
      on storage.objects for insert
      with check ( bucket_id = 'avatars' );
  4. Set up a local Supabase development environment

    main

    The Supabase Swift Examples app is designed to run against a local Supabase instance. To set this up:

    1. Install Supabase CLI: Ensure you have the Supabase CLI installed.
    2. Start Services: Navigate to the root of the supabase-swift repository and run supabase start. This initializes the API, Studio, and Inbucket (for email testing).
    3. Database Schema: The database schema is automatically applied via migrations located in /supabase/migrations/ when you run supabase start.
    4. Seed Data (Optional): To populate your local database with sample data, run supabase db reset.

    Local Service Endpoints:

    • API: http://127.0.0.1:54321
    • Studio: http://127.0.0.1:54323
    • Inbucket (Email Testing): http://127.0.0.1:54324
    # Navigate to the root directory
    cd /path/to/supabase-swift
    
    # Start Supabase local development
    supabase start
    
    # Optional: Load seed data
    supabase db reset
  5. Get Started with the User Management Example

    main

    To run the User Management example, follow these steps:

    1. Create a Supabase Project: Set up a new project in your Supabase dashboard.
    2. Configure Credentials: Copy your project credentials (URL and Anon Key) into the Supabase.swift file within the project.
    3. Run the App: Open the project in Xcode and run it on a physical device or a simulator.

    This example demonstrates:

    • Supabase Auth: Signing users in using magic links.
    • Supabase Database: Storing and retrieving user profile data.
    • Supabase Storage: Managing image files (avatars).
  6. Test email authentication using Inbucket

    main

    When running Supabase locally, emails are not sent to real addresses. Instead, they are captured by Inbucket.

    1. Start your local Supabase instance.
    2. Open http://127.0.0.1:54324 in your browser.
    3. Perform a sign-up or request a magic link in the app using any email (e.g., test@example.com).
    4. Check Inbucket to find the confirmation email, click the magic link, or copy the verification code.
  7. Initialize the Supabase client

    main

    To start using Supabase, initialize a SupabaseClient with your project's URL and your public API key.

    let client = SupabaseClient(
        supabaseURL: URL(string: "https://xyzcompany.supabase.co")!,
        supabaseKey: "your-publishable-key"
    )
  8. Configure MetaMask (Web3) Sign-In

    main

    To use the MetaMask sign-in example, follow these specific requirements:

    1. Supabase Configuration: Enable the [auth.web3.ethereum] authentication method in your Supabase project settings.
    2. Redirect URL Allow-list: Add http://localhost:3000 to your Supabase project's Authentication → URL Configuration → Additional Redirect URLs. The backend requires this exact string to validate the SIWE message.
    3. Hardware: Use a physical device with the MetaMask Mobile app installed. The app-to-app handoff does not work on the iOS Simulator.
    4. Deep Linking: The app uses the custom URL scheme com.supabase.swift-examples.metamask which is pre-configured in the Info.plist.
  9. Configure OAuth providers for testing

    main

    To test social authentication in the examples app, you must configure the following in your Info.plist:

    Google Sign-In

    1. Create credentials in Google Cloud Console.
    2. Enable Google Sign-In API.
    3. Update Info.plist with:
      • {{ YOUR_IOS_CLIENT_ID }}
      • {{ YOUR_SERVER_CLIENT_ID }}
      • {{ DOT_REVERSED_IOS_CLIENT_ID }}

    Facebook Sign-In

    1. Create an app in Facebook Developers Console.
    2. Add the iOS platform.
    3. Update Info.plist with:
      • {{ FACEBOOK APP ID }}
      • {{ FACEBOOK CLIENT TOKEN }}

    Apple Sign-In

    • Ensure the Sign in with Apple capability is enabled in your Xcode project settings.
  10. Install the Supabase Swift SDK

    main

    You can install the full Supabase client or individual libraries via Swift Package Manager.

    To install the full client, add https://github.com/supabase/supabase-swift.git as a dependency in your Package.swift and depend on the Supabase product.

    Available individual libraries:

    • Auth: User authentication and session management
    • PostgREST: Query your Postgres database via REST
    • Realtime: Subscribe to database changes over WebSocket
    • Storage: Manage files and objects
    • Functions: Invoke Supabase Edge Functions
    let package = Package(
        ...
        dependencies: [
            .package(
                url: "https://github.com/supabase/supabase-swift.git",
                from: "2.0.0"
            ),
        ],
        targets: [
            .target(
                name: "YourTargetName",
                dependencies: [
                    .product(name: "Supabase", package: "supabase-swift")
                ]
            )
        ]
    )