Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to initialize sqlite database for a user with SwiftUI?

I have this function that initializes a database (basically copied from the documentation of SQLite.swift).

func createDB() {
    let paths = FileManager.default.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask)
    let documentsDirectory = paths[0]
    print(documentsDirectory)
    do {
        // creates new if it doesnt exist
        let db = try Connection("\(documentsDirectory)/dbtest.sqlite3")
    } catch {
        print(error)
    }
}

Right now I just have it within the @main struct.

@main
struct MyApp: App {
    ...
    createDB()
}

In the SwiftUI world, how would you create a global DB object that I can use throughout a session (user having the app open)? Or is creating it here fine?

like image 773
Paul Avatar asked May 19 '26 12:05

Paul


1 Answers

There are various good / bad / ugly ways of handling this, and creating the db in main struct, may be a considered a bad way.

A better approach is to wrap all sqlite code in one of your own implementations. As an example, check Wrapping the Database Connection section in this tutorial

Also in the spirit of not writing a "link only" answer, below is a snippet from the same section

class SQLiteDatabase {
    private let dbPointer: OpaquePointer?
    private init(dbPointer: OpaquePointer?) {
        self.dbPointer = dbPointer
    }
    deinit {
      sqlite3_close(dbPointer)
    }
}
like image 111
Swapnil Luktuke Avatar answered May 21 '26 12:05

Swapnil Luktuke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!