Giter Club home page Giter Club logo

supabase-swift's Introduction

supabase-swift

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

Supported Platforms

Platform Support
iOS
macOS
watchOS
tvOS
visionOS
Linux ☑️
Windows ☑️

✅ Official support

☑️ Works but not officially supported, and not guaranttee to keep working on future versions of the library.

Usage

Install the library using the Swift Package Manager.

let package = Package(
    ...
    dependencies: [
        ...
        .package(
            url: "https://github.com/supabase-community/supabase-swift.git",
            from: "2.0.0"
        ),
    ],
    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-community/supabase-swift.git for the url when Xcode asks.

If you don't want the full Supabase environment, you can also add individual packages, such as Functions, Auth, Realtime, Storage, or PostgREST.

Then you're able to import the package and establish the connection with the database.

/// Create a single supabase client for interacting with your database
let client = SupabaseClient(supabaseURL: URL(string: "https://xyzcompany.supabase.co")!, supabaseKey: "public-anon-key")

Initialize with custom options

let client = SupabaseClient(
    supabaseURL: URL(string: "https://xyzcompany.supabase.co")!, 
    supabaseKey: "public-anon-key",
    options: SupabaseClientOptions(
        db: .init(
            schema: "public"
        ),
        auth: .init(
            storage: MyCustomLocalStorage(),
            flowType: .pkce
        ),
        global: .init(
            headers: ["x-my-custom-header": "my-app-name"],
            session: URLSession.myCustomSession
        )
    )
)

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

supabase-swift's People

Contributors

grdsdev avatar satishbabariya avatar github-actions[bot] avatar dependabot[bot] avatar angcosmin avatar leomehlig avatar thecoolwinter avatar maail avatar gentilijuanmanuel avatar iamlouislab avatar mbarnach avatar mdloucks avatar mpross512 avatar saurabhjamadagni avatar theolampert avatar tyirenkyi avatar tmn avatar multimokia avatar zunda-pixel avatar jxhug avatar james-william-r avatar jknlsn avatar glowcap avatar colgates avatar christopheprat avatar bryandubno avatar brianmichel avatar junjielu avatar

Stargazers

Raniera Te Moni avatar Kevin Wilfried avatar Jiwoong CHOI avatar mcmay avatar Deandra avatar kk4ch1 avatar  avatar lasse avatar  avatar Chelsey Baker avatar Sebastijan Zindl avatar  avatar Ertem Biyik  avatar deZ avatar Alex Luna avatar L.Longheval avatar  avatar Suhail Khan avatar  avatar  avatar Muhammad Ilham Jaya  avatar Yali Hart avatar Tanmay avatar laiso avatar Ashesh Patel avatar Luis Pereira avatar George Kontridze avatar whitelips avatar joshroche avatar Taguchi-wq avatar Antoine Marcadet avatar  avatar Amos Gyamfi avatar Jan Kodeš avatar  avatar 张嘉夫 avatar Philipp Preiner avatar Dani Plata avatar Karson Miller avatar Ishaan Bedi avatar CHIH-HAO CHEN avatar Aditya Tyagi avatar Hilmy Veradin avatar Arun avatar George  avatar Levin Van avatar Daniel Tarazona avatar Jon Page avatar Admir Šaheta avatar Hannes Bleicher avatar Joe Kiley avatar Alisa Wu avatar Sebastien Augbsurger avatar  avatar Fikret avatar Roy avatar Shelton Brown avatar Alex Vozniuk avatar brendan avatar  avatar YOO avatar  avatar  avatar Jay avatar  Vivek Rp avatar Heiko Witte avatar Simon Rice avatar  avatar Leandro Pessini avatar Ashu avatar Thomas avatar Crossley Rozario avatar Tiago Henriques avatar Andrey Oshev avatar Alex Rigler avatar Reo avatar adamz avatar Alzea Arafat avatar Luke Leach avatar Anubhav Singh avatar Gonzalo Nuñez  avatar Natasha Murashev avatar Ashley Mills avatar Caleb Forestal |  avatar hejsfj avatar Daniel Hsu avatar ubeezy avatar Krish Mittal avatar  avatar  avatar  avatar Amisha Canopas avatar Kody Deda avatar grep avatar Michael Carvin avatar Tyler avatar Stan avatar Anton Prokhorov avatar  avatar Raphael avatar

Watchers

Tom Ashley avatar Terry Sutton avatar Mark Burggraf avatar Div Arora avatar Ant Wilson avatar Ivan Vasilov avatar Hieu avatar Joe Fabisevich avatar James Cloos avatar Daniel Simons avatar Stas avatar Filipe Cabaço avatar Raghavendra Badaskar avatar Andrew Kelley avatar Richard Torcato avatar  avatar  avatar Rors  avatar  avatar Jonathan Summers-Muir avatar Jon Meyers avatar  avatar Tyler avatar Joshen Lim avatar Troy Deville avatar divit avatar  avatar Ville Heikkilä avatar  avatar ct avatar

supabase-swift's Issues

[tvOS] Allow setting auth tokens manually

We are developing a digital signage app for Apple TV (tvOS) and are considering to use Supabase as our backend service. While creating a proof of concept I stumbled upon a problem with authenticating. Since there is no web browser on tvOS the traditional auth flow won't work.

Instead the user needs to sign in on another device and we need to set auth tokens manually on the SupabaseClient instance in our tvOS app. E.g. there might be a companion sign-in app on iOS that transfers auth tokens securely over to the tvOS app.
But as of now there is no way to set auth tokens manually on the client itself.

In supabase-js we have a method called setAuth() that lets you override the access token. Since the app basically does not have any user interaction at all, we also need to set the refresh token in order to stay authenticated while the app shows its content.

Headers missing

Bug report

Describe the bug

Some headers aren't set when initializing a SupabaseClient and make it impossible to use the storage module

To Reproduce

Initialize a SupabaseClient and use any method from the subclass storage (e.g. client.storage.listBuckets())

This issue is related to this issue from storage-swift but it needs to be fixed from this repo and not from supabase-community/storage-swift.
Please see this comment fro more information.

listBuckets doesn't work

Bug report

Listing buckets crashes the app.

Describe the bug

When I try to use .listBuckets() as mentioned here, my app throws an error (caught using fatalError with the name "Error"). The error status code is 400.

To Reproduce

  • Initialize the client
  • Run try await client.storage.listBuckets()

System information

  • OS: macOS

Supabase installation doesn't work

I've followed steps to install Supabase but Xcode(v13.1) unable to import Supabase for an iOS app

How I installed?
SPM - Search by URL and then added the package successfully

Debugging:
Tried

  • Clean Build folder
  • Restart Xcode

Actual result:

  • Unable to import it
    CleanShot 2022-03-16 at 17 24 13@2x

Fails to build due to PostgREST master branch dependency

Bug report

Describe the bug

Build attempts fail due to changes in PostgREST master branch

  • FunctionsClient init change
  • PostgrestClient init change
  • FunctionsHTTPClient removal
  • PostgrestHTTPClient removal

To Reproduce

  1. Create new project (or have existing project)
  2. Add supabase-swift SPM dependency as described in README
  3. Attempt to build the project
  4. See errors in SupabaseClient.swift

Expected behavior

Should build without issue

Screenshots

Screenshot 2023-01-02 at 1 00 27 PM

Additional context

Switching to the Release Candidate #45 most recent commit solves the issue (albeit not ideal)

.package(name: "Supabase", url: "https://github.com/supabase/supabase-swift.git", branch: "release-candidate")

It seems like shifting the master branch to tagged dependencies from here on would avoid issues like these popping up

failing to build on widget: symbol(s) not found for architecture arm64

Bug report

Describe the bug

Can't build my widget extension after using Supabase module: ld: symbol(s) not found for architecture arm64

To Reproduce

  1. Create a widget extension for your app
  2. Try to use Supabase package
  3. Enjoy

Here is my code: https://gist.github.com/obito/2f750bc0df1f1b2faac350315dc88f88

Expected behavior

Should not crash when trying to build, like on my iOS app.

Screenshots

No screenshots, but here is the full report dump: https://hastebin.com/share/ibakesinof.php

System information

Macbook Air M1: Darwin macbook-2.local 22.4.0 Darwin Kernel Version 22.4.0: Mon Mar 6 21:00:41 PST 2023; root:xnu-8796.101.5~3/RELEASE_ARM64_T8103 arm64

Additional context

I don't really understand why this issue happens only on the widget extension part. It seems to look like it's failing to build because CMake/something was not build for the ARM64 architecture, when there shouldn't be any difference between an app and a widget (maybe?).

Auth session doesn't refresh when using database

Bug report

Describe the bug

If my JWT has expired since I last called supabaseClient.auth.session, and I try to execute a command using supabaseClient.database, I get an error about the JWT being expired. I have to work around this by calling _ = supabaseClient.auth.session before every database call to force it to refresh the token.

To Reproduce

  1. Log in using Supabase Auth
  2. Wait for the token to expire
  3. Try to perform an operation on a database

Expected behavior

I would expect the session to automatically be refreshed before attempting the database operation.

System information

  • OS: macOS
  • Version of supabase-swift: 0.2.1

Can not create Client

Can't create client

Client creation like in the readme doesn't work

I am trying to create a new client to test the supabase login in my swift-ui project, however when I try to create the client with:

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

I get the error Cannot convert value of type 'String' to expected argument type 'URL'

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

I get the error No exact matches in call to initializer

Am I doing something wrong or is the readme not up to date?

Expected behavior

Create a client

System information

  • OS: macOS
  • Version of supabase-switft: 0.2.1

Broken example in README.md

Bug report

The CRUD insert example found in README.MD is broken. This caused a lot of frustration getting started.

Describe the bug

When running the example found in README.MD

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("### Insert Error: \(error)")
    }
}

Where InsertModel is defined as (as the README says "Using the same model as before")

struct InsertModel: Encodable {
    let id: Int? // you can choose to omit this depending on how you've setup your table
    let title: String?
    let desc: String?
}

You are greeted with the following error in XCode:

Cannot convert value of type 'Void' to specified type '[InsertModel]'

This is fixable by redefining InsertModel as follows:

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?
}

Which fixes this error. However, when attempting to cast to InsertModel as follows in the example:

let response: InsertModel = try await query.execute().value

You receive the following error

typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))

To address this, it must be fit into an array as follow:
let response: [InsertModel] = try await query.execute().value

This finally allows you to access the underlying data.

To Reproduce

To reproduce, run the code found in the example README and perform the aforementioned changes.

System information

  • OS: [MacOS]
  • Version of Supabase [0.1.3]
    Using the Package.swift import:
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
        )
    ]
)

Can't sign in another google account

When I login with goggle account, after signOut I can't sign in another google account. Step flow:

  • Login with google account using: SPBase.shared.client.auth.signIn(provider: .google, options: options)
  • SignOut using: SPBase.shared.client.auth.signOut()
  • When login with google account again:

Expected: Show login screen with allow input new account

Simulator Screen Shot - iPhone 8 - 2022-06-28 at 17 08 07

Actual: Auto login with old account

SPM Error when compiling

Bug report

Describe the bug

The compiler complains when integrating supabase-swift into a project:

error: The package product 'Supabase' cannot be used as a dependency of this target because it uses unsafe build flags. (in target 'MyApp' from project 'MyApp')

To Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

  1. Create new app in Xcode
  2. Add swift package
  3. Import the framework
  4. Try to compile
  5. See error above

Expected behavior

Should be able to compile.

Screenshots

If applicable, add screenshots to help explain your problem.

System information

macOS Ventura 10.13.1
Xcode 14.2 (14C18)

Additional context

Add any other context about the problem here.

[Request] When are docs for Realtime and Storage coming?

I played around with Realtime based on the realtime-swift docs, but I just couldn't get it to work.
It would be great if you added docs for both of those features, since it has been months since anything changed with them.

X-Client-Info

we're rolling out a header similar to Stripe's App-Data in all of the client libs so issues can be debugged more easily between the client and the backend

the javascript libs are done already: supabase/supabase-js#238

the format is: X-Client-Info: supabase-js/1.11.0

for client libs that wrap others (like how supabase-js wraps gotrue-js) we allow the wrapper lib to overwrite the wrapped lib's header (given that we can infer the gotrue-js version based on which supabase-js was used to make the call)

any help with rolling this out here would be incredible, it also ideally would be rolled out into the wrapped libs (postgrest-swift etc.)

Auto-refreshing JWT randomly expires in 0.0.8

Auto-refresh now works, but only half the time

It occasionally throws a PGRST301 error on query execution (401 on Supabase)

Retrying the query multiple times fixes this, but I don't think it's a good solution long-term

Maybe it issues a new token on query but passes only on the next one?

Allow `GoTrueClient` injectable to SupabaseClient initializer

Feature request

It would be great a GoTrueClient to be injected as a parameter to SupabaseClient initializer.

Is your feature request related to a problem? Please describe.

We have a specific Keychain configuration that we need to inject to the GoTrueClient (whose initializers already support injecting their own KeychainStorage/GoTrueLocalStorage. Our app will not be able to use the defacto Keychain location that is being provided in the GoTrueClient(...) init that this initializer is using.

Describe the solution you'd like

This could be as easy as allowing a new constructor

  public init(
    supabaseURL: URL,
    supabaseKey: String,
    schema: String = "public",
    headers: [String: String] = [:],
    httpClient: HTTPClient = HTTPClient(),
    authClient: GoTrueClient
  ) {

It seems that the auth client does depend on the headers, so maybe allowing some kind of convenience method on GoTrueClient(...) to construct it based upon the existing supabaseURL and supabaseKey which are added via the defaultHeaders property, would be helpful.

Describe alternatives you've considered

Instead of being provided to the initializer, the auth property could become a var for an automatic get or there could be another function like setAuthClient(...) that is exposed. But that would probably introduce some weird conditions that are tougher to reason about rather than just injecting in the init(...)

Additional Context

If either approach is acceptable, I'm happy to write it up and put up a PR.
Thanks.

Ability to add own headers

Feature request

I am in the need to send my own Authorization token in the header rather than using the Auth session that Supabase provides and currently its impossible to do so - or I haven't found the way to do it. It would be interesting to be able to add your own custom headers in the init of the client since its where you set your defaultHeaders.

Describe the solution you'd like

My proposal is to add in this init the ability to pass your own custom headers that are merged into the default Supabase ones.

public init(
    supabaseURL: URL,
    supabaseKey: String,
    schema: String = "public",
    httpClient: HTTPClient = HTTPClient(),
customHeaders: [String: String]? = nil
  ) {
    self.supabaseURL = supabaseURL
    self.supabaseKey = supabaseKey
    self.schema = schema
    self.httpClient = httpClient

    defaultHeaders = [
      "X-Client-Info": "supabase-swift/\(version)",
      "apikey": supabaseKey,
    ]

if let customHeaders = customHeaders {
            defaultHeaders = defaultHeaders.merging(customHeaders) { (_, new) in new }
        }

    auth = GoTrueClient(
      url: supabaseURL.appendingPathComponent("/auth/v1"),
      headers: defaultHeaders
    )
  }

This way the user can overwrite the headers if they consider it so - at their own risk.

Insert a todo into the database example throws an error. Suggested fix.

Bug report

Describe the bug

The code for adding a Todo throws several errors.

There appears to be an error in the JSON serialization and the client database insertion says "from" when the method should be "form. Changing that part works. But I'm unsure if the data is being properly serialized.

 do {
        let jsonData: Data = try JSONEncoder().encode(todo)
        let jsonDict  = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments)
        try client.database.form("todos")
            .insert(values: jsonDict as! [String : Any])
                           .execute { results in
                            
                            
                            print(results)
            // Handle response
        }
    } catch {
       print("Error inserting the todo: \(error)")
    }

To Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

  1. Add the example for adding a Todo.

The following error messages appear:

  • Cannot convert value of type 'Any' to specified type '[String : Any]'
  • Closure expression is unused
  • Unable to infer type of a closure parameter 'results' in the current context

Expected behavior

Ideally the code wouldn't throw any error messages.

System information

  • Xcode 12.5.1

Please introduce tags

Please introduce tags and releases to this package. As you know Swift Playgrounds 4 got released, but it only supports SPM packages by version number, not by branch. Thus it is currently impossible to use this SDK in a Playgrounds project.

Release Number

Bug report

Is there any chance we could create a new release with version 0.0.1 or something small? It would help when integrating this package with other packages where SPM requires a version number.

App Store Ready

Is this library ready for use in a production app that can go in the App Store? If not, any ETA on when it would be ready by?

Is this production ready?

Guessing from contribution activity that it's not, but just wanted to check to be sure.. Hoping to use Google SSO in an app Im working on

iOS 12

What can I do to enable support for IOS12?
TX.

Invoking edge function always results in `unacceptableStatusCode(404)`

Bug report

Describe the bug

When trying to invoke any Edge Function from supabase-swift client context (with or without invoke options) throws an error unacceptableStatusCode(404). Call does not register in the Edge Functions log browser, but it appears in the API Edge Network log browser as a 404 (see below) using a different invocation URL format:

functions-swift

https://xxx.supabase.co/functions/v1/preview-issue

Edge Functions API documentation

https://xxx.functions.supabase.co/preview-issue

The function name is correct (preview-issue) and can be accessed using Edge Functions API, so it appears that the invocation URL for functions-swift uses an incorrect format:

https://github.com/supabase-community/supabase-swift/blob/8292bf9a8eb21ca1bcfbd249ed84e67776e5ee2f/Sources/Supabase/SupabaseClient.swift#L47-L53

To Reproduce

Invoke a Edge Function using the following signature (after setting up your Supabase Swift client:

do {
    try await client.functions.invoke(functionName: "preview-issue", invokeOptions: .init(headers: ["param": "some-string"]))
} catch {
    throw error
}

Expected behavior

  • Invocation succeeds and the Edge Function result returns expected response
  • Invocation gets registered in the Edge Functions log browser

Logs

Log ID
4edd9ee6-9cff-47c3-a476-8426515f3ad2

Log Timestamp (UTC)
2023-02-12T12:24:31.132Z

Log Event Message
POST | 404 | 213.205.242.39 | 79854d3a4d27777a | https://xxx.supabase.co/functions/v1/preview-issue

Log Metadata
[
  {
    "request": [
      {
        "headers": [
          {
            "accept": "application/json",
            "cf_cache_status": null,
            "cf_connecting_ip": "213.205.242.39",
            "cf_ipcountry": "GB",
            "cf_ray": "79854d3a4d27777a",
            "content_length": "0",
            "content_location": null,
            "content_range": null,
            "content_type": null,
            "date": null,
            "host": "xxx.supabase.co",
            "referer": null,
            "sb_gateway_version": null,
            "user_agent": "iOS/1 CFNetwork/1402.0.8 Darwin/22.3.0",
            "x_client_info": "functions-swift/0.2.0",
            "x_forwarded_proto": "https",
            "x_forwarded_user_agent": null,
            "x_kong_proxy_latency": null,
            "x_kong_upstream_latency": null,
            "x_real_ip": "213.205.242.39"
          }
        ],
        "host": "xxx.supabase.co",
        "method": "POST",
        "path": "/functions/v1/preview-issue",
        "port": null,
        "protocol": "https:",
        "sb": [],
        "search": null,
        "url": "https://xxx.supabase.co/functions/v1/preview-issue"
      }
    ],
    "response": [
      {
        "headers": [
          {
            "cf_cache_status": "DYNAMIC",
            "cf_ray": "79854d3a7723777a-LHR",
            "content_length": "48",
            "content_location": null,
            "content_range": null,
            "content_type": "application/json; charset=utf-8",
            "date": "Sun, 12 Feb 2023 12:24:31 GMT",
            "sb_gateway_mode": null,
            "sb_gateway_version": "1",
            "transfer_encoding": null,
            "x_kong_proxy_latency": null,
            "x_kong_upstream_latency": null
          }
        ],
        "origin_time": 37,
        "status_code": 404
      }
    ]
  }
]

System information

  • OS: iOS 16.1
  • Swift: 5.7
  • Xcode: 14.2
  • supabase-swift: 0.1.2
  • functions-swift: 0.2.0

Insert doesn‘t return inserted row

Using this code I insert a row into a todo table.
Expectation was, that execute returns the row but it doesn‘t.
But I need the inserted row because „id“ is an autogenerated column.
Any way to achieve this?


func createTodo(withTitle title: String) async {
        let todo = Todo(id: nil, title: title, done: false)
        let query = client
            .database
            .from("todos")
            .insert(values: todo)
        query.execute { results in
            switch results {
            case let .success(result):
                print (result)
                // self.todos.append(result.data) // I can‘t do that sice I receive no resulting data
            case let .failure(error):
                Print(error.localizedDescription)
            }
        }
    }

Searching across multiple columns (and matching substrings)

I have a table called fun_facts with the following columns:
id: int (primary key)
content: text
keywords: text
tag: text

Here's an example of a row:
id: 123
content: "A crocodile cannot stick its tongue out"
keywords: "impossible animals body funny"
tag: "fact123"

Using the Supabase Swift client, what's the best/recommended way to search across multiple table columns? I want the example row above to show up if I search for terms such as the following:

  • "croc"
  • "tongue crocodile"
  • "animal funny"
  • "impossible"
  • "fact123"
  • "123"

Thanks in advance!

can't seem to fetch rows.

Bug report

I have this a test org and it's returning results fine using python
https://gist.github.com/johndpope/4bdf87792c034fadb157766c702253d0

Describe the bug

When running same query
I get no results in swift version.

Screenshot 2022-11-18 at 7 43 44 am

result: Optional(PostgREST.PostgrestResponse<()>(underlyingResponse: Get.Response<()>(value: (), response: <NSHTTPURLResponse: 0x600001263020> { URL: https://qfwzdkpmyzajmmvupgzy.supabase.co/rest/v1/tweets?select=* } { Status Code: 200, Headers {
    "Access-Control-Allow-Origin" =     (
        "*"
    );
    "Alt-Svc" =     (
        "h3=\":443\"; ma=86400, h3-29=\":443\"; ma=86400"
    );
    "Content-Encoding" =     (
        br
    );
    "Content-Location" =     (
        "/tweets?select=%2A"
    );
    "Content-Type" =     (
        "application/json; charset=utf-8"
    );
    Date =     (
        "Thu, 17 Nov 2022 20:43:22 GMT"
    );
    Server =     (
        cloudflare
    );
    Vary =     (
        "Accept-Encoding"
    );
    Via =     (
        "kong/2.8.1"
    );
    "cf-cache-status" =     (
        DYNAMIC
    );
    "cf-ray" =     (
        "76bb4c4babd6a97a-SYD"
    );
    "content-profile" =     (
        public
    );
    "content-range" =     (
        "0-999/*"
    );
    "sb-gateway-version" =     (
        1
    );
    "x-kong-proxy-latency" =     (
        0
    );
    "x-kong-upstream-latency" =     (
        15
    );
} }, data: 422860 bytes, task: LocalDataTask <47B6B060-DF8F-4921-AE38-CF831D362865>.<1>, metrics: Optional((Task Interval) <_NSConcreteDateInterval: 0x60000125f3e0> (Start Date) 2022-11-17 20:43:20 +0000 + (Duration) 2.450190 seconds = (End Date) 2022-11-17 20:43:22 +0000
(Redirect Count) 0
(Transaction Metrics) (Request) <NSMutableURLRequest: 0x60000101c320> { URL: https://qfwzdkpmyzajmmvupgzy.supabase.co/rest/v1/tweets?select=* }
(Response) <NSHTTPURLResponse: 0x600001262240> { URL: https://qfwzdkpmyzajmmvupgzy.supabase.co/rest/v1/tweets?select=* } { Status Code: 200, Headers {
    "Access-Control-Allow-Origin" =     (
        "*"
    );
    "Alt-Svc" =     (
        "h3=\":443\"; ma=86400, h3-29=\":443\"; ma=86400"
    );
    "Content-Encoding" =     (
        br
    );
    "Content-Location" =     (
        "/tweets?select=%2A"
    );
    "Content-Type" =     (
        "application/json; charset=utf-8"
    );
    Date =     (
        "Thu, 17 Nov 2022 20:27:54 GMT"
    );
    Server =     (
        cloudflare
    );
    Vary =     (
        "Accept-Encoding"
    );
    Via =     (
        "kong/2.8.1"
    );
    "cf-cache-status" =     (
        DYNAMIC
    );
    "cf-ray" =     (
        "76bb35a7adf3a974-SYD"
    );
    "content-profile" =     (
        public
    );
    "content-range" =     (
        "0-999/*"
    );
    "sb-gateway-version" =     (
        1
    );
    "x-kong-proxy-latency" =     (
        1
    );
    "x-kong-upstream-latency" =     (
        15
    );
} }
(Fetch Start) 2022-11-17 20:43:20 +0000
(Domain Lookup Start) (null)
(Domain Lookup End) (null)
(Connect Start) (null)
(Secure Connection Start) (null)
(Secure Connection End) (null)
(Connect End) (null)
(Request Start) 2022-11-17 20:43:20 +0000
(Request End) 2022-11-17 20:43:20 +0000
(Response Start) 2022-11-17 20:43:20 +0000
(Response End) 2022-11-17 20:43:20 +0000
(Protocol Name) (null)
(Proxy Connection) NO
(Reused Connection) NO
(Fetch Type) Local Cache
(Request Header Bytes) 0
(Request Body Transfer Bytes) 0
(Request Body Bytes) 0
(Response Header Bytes) 0
(Response Body Transfer Bytes) 0
(Response Body Bytes) 0
(Local Address) (null)
(Local Port) (null)
(Remote Address) (null)
(Remote Port) (null)
(TLS Protocol Version) 0x0000
(TLS Cipher Suite) 0x0000
(Cellular) NO
(Expensive) NO
(Constrained) NO
(Multipath) NO

(Request) <NSURLRequest: 0x60000101caf0> { URL: https://qfwzdkpmyzajmmvupgzy.supabase.co/rest/v1/tweets?select=* }
(Response) <NSHTTPURLResponse: 0x60000124e260> { URL: https://qfwzdkpmyzajmmvupgzy.supabase.co/rest/v1/tweets?select=* } { Status Code: 200, Headers {
    "Access-Control-Allow-Origin" =     (
        "*"
    );
    "Alt-Svc" =     (
        "h3=\":443\"; ma=86400, h3-29=\":443\"; ma=86400"
    );
    "Content-Encoding" =     (
        br
    );
    "Content-Location" =     (
        "/tweets?select=%2A"
    );
    "Content-Type" =     (
        "application/json; charset=utf-8"
    );
    Date =     (
        "Thu, 17 Nov 2022 20:43:22 GMT"
    );
    Server =     (
        cloudflare
    );
    Vary =     (
        "Accept-Encoding"
    );
    Via =     (
        "kong/2.8.1"
    );
    "cf-cache-status" =     (
        DYNAMIC
    );
    "cf-ray" =     (
        "76bb4c4babd6a97a-SYD"
    );
    "content-profile" =     (
        public
    );
    "content-range" =     (
        "0-999/*"
    );
    "sb-gateway-version" =     (
        1
    );
    "x-kong-proxy-latency" =     (
        0
    );
    "x-kong-upstream-latency" =     (
        15
    );
} }
(Fetch Start) 2022-11-17 20:43:20 +0000
(Domain Lookup Start) 2022-11-17 20:43:20 +0000
(Domain Lookup End) 2022-11-17 20:43:20 +0000
(Connect Start) 2022-11-17 20:43:20 +0000
(Secure Connection Start) 2022-11-17 20:43:20 +0000
(Secure Connection End) 2022-11-17 20:43:20 +0000
(Connect End) 2022-11-17 20:43:20 +0000
(Request Start) 2022-11-17 20:43:20 +0000
(Request End) 2022-11-17 20:43:20 +0000
(Response Start) 2022-11-17 20:43:22 +0000
(Response End) 2022-11-17 20:43:22 +0000
(Protocol Name) h3
(Proxy Connection) NO
(Reused Connection) NO
(Fetch Type) Network Load
(Request Header Bytes) 998
(Request Body Transfer Bytes) 0
(Request Body Bytes) 0
(Response Header Bytes) 295
(Response Body Transfer Bytes) 110951
(Response Body Bytes) 422860
(Local Address) 192.168.1.100
(Local Port) 62732
(Remote Address) 104.18.26.135
(Remote Port) 443
(TLS Protocol Version) 0x0304
(TLS Cipher Suite) 0x1301
(Cellular) NO
(Expensive) NO
(Constrained) NO
(Multipath) NO

)), count: nil))

To Reproduce

    override func viewDidLoad() {
        super.viewDidLoad()
        setupDatabase()
    }
    
    func setupDatabase() {
        let SUPABASE_URL = URL(string:"https://qfwzdkpmyzajmmvupgzy.supabase.co")!
        let ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InFmd3pka3BteXpham1tdnVwZ3p5Iiwicm9sZSI6ImFub24iLCJpYXQiOjE2NjgxMzAzMjYsImV4cCI6MTk4MzcwNjMyNn0.kEweOMrRSJ0mtOIXnsRmbNxf4yqoZAZf398jlGgSxtQ"
        self.client = SupabaseClient(supabaseURL: SUPABASE_URL, supabaseKey: ANON_KEY)
        Task {
            await fetchRows();
        }
    }
    

    func fetchRows() async  {
        
        let result = try? await self.client?.database.from("tweets").select(columns: "*").execute();
        print("result:",result.debugDescription);
    }

Steps to reproduce the behavior, please provide code snippets or a repository:
I'm on release-candidate branch

Expected behavior

running python version - I get results back
Screenshot 2022-11-18 at 7 45 15 am

but on ios - I get results = nil

Screenshots

If applicable, add screenshots to help explain your problem.

System information

  • OS: macos - ventura
  • Version of Node.js: swift release candidate branch 0.0.9

Additional context

I've successfully used and got data from superbase in another project - not sure what's going on here.
maybe to do with async stuff?

OAuth Sign in with Apple (cannot open the page because the address is invalid)

I am trying to set up sign-in with apple for my Swift project. The account is being created on Supabase side but I can not see the email associated with the account.

trying to figure out what is the problem here and I am quite stumped.

I think it could be that the NotificationCenter.default.post Isn't posting and there for the observer isn't working either

I have also opened a ticket in the discord: https://discord.com/channels/839993398554656828/1084966472163536926

Crashing On Query Execution

MacOS: Monterey (12.2.2)
XCode Version 13.3 (13E113)

I seem to be having an issue getting this to work correctly. Trying to execute a query crashes as soon it begins.
Although it could be a problem with my code as I'm fairly new to swift.

My Environment variables are correct as I stepped through them before crash

import SwiftUI
import Supabase

struct ContentView: View {
    @StateObject private var model = ContentViewModel()
    

    var body: some View {
        VStack {
            List(model.lessons) { lesson in
                        Text("\(lesson.title): \(lesson.description)")
                    }
        }
        .onAppear {
           model.getLessons()
        }
    }
}

class ContentViewModel: ObservableObject {
    @Published var lessons: [Lesson] = []    
    let supabaseUrl = URL(string: ProcessInfo.processInfo.environment["SUPABASE_URL"]!)
    let supabaseKey = ProcessInfo.processInfo.environment["SUPABASE_KEY"]!
    
    lazy var client = SupabaseClient(supabaseURL: supabaseUrl!,supabaseKey: supabaseKey)
    

    
    // Retrieve all lessons
    func getLessons() {
        print("Retrieving all todo's from database")
        
        let query = client.database.from("lessons")
            .select()
        
        query.execute { results in
            switch results {
                case let .success(response):
                    let lessons = try? response.decoded(to: [Lesson].self)
                    self.lessons = lessons!
                case let .failure(error):
                    print(error.localizedDescription)
            }
        }
        
    }

}


struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Clarification on signed in row level security access via jwt

Improve documentation

let client = SupabaseClient(supabaseURL: SUPABASE_URL, supabaseKey: ANON_KEY)

Describe the problem

how can a signed in user access database with row level security?
is there a way to switch in the jwt once we have it -
eg.
client.updateJWT( supabaseKey: authorisedJWT);

I'm working on a sign in with apple / nodejs - native login flow - but once I have the jwt - how can I then proceed to use it....
https://github.com/johndpope/Sign-in-with-Apple-for-supabase

Add Linux Support

Feature request

Add support for supabase-swift on Linux.

Is your feature request related to a problem? Please describe.

I'm trying to build a Swift on the server application and was hoping to use the Supabase SDK to do so, but not able to right now.

Describe the solution you'd like

It looks like it mostly should work, but ran into an issue around some URLSession APIs that don't seem to be available on Linux. I believe it should be something you can work around, I found this blog post discussing the subject, and while I don't know the library's history I saw some #if canImport(FoundationNetworking) checks in the code base already so I suspect some Linux support was at least attempted.

Describe alternatives you've considered

Using the REST API, but making this change would benefit more than just me, it would open up a whole class of possibilities for anyone using Supabase from the server.

Additional context

This is the failed build log for the issue I'm running into.

/__w/SupabaseSample/SupabaseSample/.build/checkouts/storage-swift/Sources/SupabaseStorage/StorageHTTPClient.swift:4:25: error: cannot find type 'URLRequest' in scope
  func fetch(_ request: URLRequest) async throws -> (Data, HTTPURLResponse)
						^~~~~~~~~~
/__w/SupabaseSample/SupabaseSample/.build/checkouts/storage-swift/Sources/SupabaseStorage/StorageHTTPClient.swift:5:26: error: cannot find type 'URLRequest' in scope
  func upload(_ request: URLRequest, from data: Data) async throws -> (Data, HTTPURLResponse)
						 ^~~~~~~~~~
/__w/SupabaseSample/SupabaseSample/.build/checkouts/storage-swift/Sources/SupabaseStorage/StorageApi.swift:52:32: error: type of expression is ambiguous without more context
	let (data, response) = try await http.fetch(request)
						   ~~~~^~~~~~~~~~~~~~~~~~~~~~~~~
/__w/SupabaseSample/SupabaseSample/.build/checkouts/storage-swift/Sources/SupabaseStorage/StorageApi.swift:53:32: error: type of expression is ambiguous without more context
	if let mimeType = response.mimeType {
					  ~~~~~~~~~^~~~~~~~
/__w/SupabaseSample/SupabaseSample/.build/checkouts/storage-swift/Sources/SupabaseStorage/StorageApi.swift:92:32: error: type of expression is ambiguous without more context
	let (data, response) = try await http.upload(request, from: formData.data)
						   ~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/__w/SupabaseSample/SupabaseSample/.build/checkouts/storage-swift/Sources/SupabaseStorage/StorageHTTPClient.swift:4:60: error: 'HTTPURLResponse' is unavailable: This type has moved to the FoundationNetworking module. Import that module to use it.
  func fetch(_ request: URLRequest) async throws -> (Data, HTTPURLResponse)
														   ^~~~~~~~~~~~~~~
Foundation.HTTPURLResponse:2:18: note: 'HTTPURLResponse' has been explicitly marked unavailable here
public typealias HTTPURLResponse = AnyObject
				 ^
/__w/SupabaseSample/SupabaseSample/.build/checkouts/storage-swift/Sources/SupabaseStorage/StorageHTTPClient.swift:5:78: error: 'HTTPURLResponse' is unavailable: This type has moved to the FoundationNetworking module. Import that module to use it.
  func upload(_ request: URLRequest, from data: Data) async throws -> (Data, HTTPURLResponse)
																			 ^~~~~~~~~~~~~~~
Foundation.HTTPURLResponse:2:18: note: 'HTTPURLResponse' has been explicitly marked unavailable here
public typealias HTTPURLResponse = AnyObject
				 ^
/__w/SupabaseSample/SupabaseSample/.build/checkouts/storage-swift/Sources/SupabaseStorage/StorageHTTPClient.swift:11:32: error: cannot find type 'URLRequest' in scope
  public func fetch(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {
							   ^~~~~~~~~~
/__w/SupabaseSample/SupabaseSample/.build/checkouts/storage-swift/Sources/SupabaseStorage/StorageHTTPClient.swift:11:67: error: 'HTTPURLResponse' is unavailable: This type has moved to the FoundationNetworking module. Import that module to use it.
  public func fetch(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {
																  ^~~~~~~~~~~~~~~
Foundation.HTTPURLResponse:2:18: note: 'HTTPURLResponse' has been explicitly marked unavailable here
public typealias HTTPURLResponse = AnyObject
				 ^
error: Error Domain=NSCocoaErrorDomain Code=260 "The file doesn’t exist."
/__w/SupabaseSample/SupabaseSample/.build/checkouts/storage-swift/Sources/SupabaseStorage/StorageHTTPClient.swift:35:16: error: cannot find type 'URLRequest' in scope
	_ request: URLRequest,
			   ^~~~~~~~~~
/__w/SupabaseSample/SupabaseSample/.build/checkouts/storage-swift/Sources/SupabaseStorage/StorageHTTPClient.swift:37:28: error: 'HTTPURLResponse' is unavailable: This type has moved to the FoundationNetworking module. Import that module to use it.
  ) async throws -> (Data, HTTPURLResponse) {
						   ^~~~~~~~~~~~~~~
Foundation.HTTPURLResponse:2:18: note: 'HTTPURLResponse' has been explicitly marked unavailable here
public typealias HTTPURLResponse = AnyObject
				 ^
/__w/SupabaseSample/SupabaseSample/.build/checkouts/storage-swift/Sources/SupabaseStorage/StorageHTTPClient.swift:13:33: error: type 'URLSession' (aka 'AnyObject') has no member 'shared'
	  let dataTask = URLSession.shared.dataTask(with: request) { data, response, error in
					 ~~~~~~~~~~ ^~~~~~
/__w/SupabaseSample/SupabaseSample/.build/checkouts/storage-swift/Sources/SupabaseStorage/StorageHTTPClient.swift:27:40: error: tuple type '(_, HTTPURLResponse)' (aka '(_, AnyObject)') is not convertible to tuple type '(Data, HTTPURLResponse)' (aka '(Data, AnyObject)')
		continuation.resume(returning: (data, httpResponse))
									   ^
/__w/SupabaseSample/SupabaseSample/.build/checkouts/storage-swift/Sources/SupabaseStorage/StorageHTTPClient.swift:39:29: error: type 'URLSession' (aka 'AnyObject') has no member 'shared'
	  let task = URLSession.shared.uploadTask(with: request, from: data) { data, response, error in
				 ~~~~~~~~~~ ^~~~~~
/__w/SupabaseSample/SupabaseSample/.build/checkouts/storage-swift/Sources/SupabaseStorage/StorageHTTPClient.swift:53:40: error: tuple type '(_, HTTPURLResponse)' (aka '(_, AnyObject)') is not convertible to tuple type '(Data, HTTPURLResponse)' (aka '(Data, AnyObject)')
		continuation.resume(returning: (data, httpResponse))

RealtimeClient is private

Bug report

Describe the bug

The realtime client realtime in the SupabaseClient class is private, making it un-accessible.

To Reproduce

See code here for the qualifier.

Expected behavior

A public qualifier is expected, in order to use the set client, like auth, storage or database

Fatal error: Attempted to read an unowned reference but object x was already deallocated

Attempting to login via:

client.auth.signIn(email: email,
                               password: password,
                               completion: { session in
                print("login result ", session)
 })

but getting a runtime crash:

Fatal error: Attempted to read an unowned reference but object 0x600001c8fc60 was already deallocated
CoreSimulator 776.3 - Device: iPhone 13 Pro Max (B3F3EB94-461D-4424-95F2-9BC730D4FB80) - Runtime: iOS 15.0 (19A339) - DeviceType: iPhone 13 Pro Max

Running iOS 15, Xcode 13 in a SwiftUI application

Realtime subscriptions don't work

Socket is connected, channel is seemingly subscribed (it fires on "receive 'ok'")

It never fires on ".all" or any other events

Only when I unsubscribe "onClose" actually fires ("onError" never fires)

Replication is enabled on all tables, it doesn't work even on non-RLS tables

In API and Postgres logs I could only see "websocket" connections, didn't see any "subscription" logs if there are supposed to be any

@GRSouza please help

I'm setting it up like Realtime Swift docs say

OAuth Login with Auth Provider Example

Feature request

I see in the gotrue RC pr the Google OAuth example was removed -
https://github.com/supabase-community/gotrue-swift/pull/37/files#diff-5040cbf573fdc1b4fc2384e97402e4a832b40b22e33b3ff33fd0568db8e35ab1

This was referenced in a few issues -
#39 (comment)
#32 (comment)
(FWIW, I was never able to get that example working.. it would never redirect back to my app)

Found another request for it
https://www.reddit.com/r/Supabase/comments/xbjkt5/guidance_needed_in_relation_to_supabase_auth_swift/

It's also being talked about in the community Discord channel (#swift) for something like this (?)

I'd also like to add that I'm new to Swift and would be interested in a full blown example app I could clone and learn from... with auth, realtime, and databasing. There's a lot of examples on the Supabase website, just none in Swift!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.