Search code examples
iosswiftuisqlite.swift

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?


Solution

  • 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)
        }
    }