Andreas Norman
Andreas Norman

Reputation: 1027

read/write database path using sqlite.swift

I'm just starting out trying sqlite.swift and databases with swift. I have prepared a database with tables and preloaded with data. I wish to select data and insert data from within the app.

The problem is that I don't understand where (in my project) to put my database.db file in order for the app to find it.

my connection code:

let path = NSSearchPathForDirectoriesInDomains(
    .documentDirectory, .userDomainMask, true
    ).first!

do {
    db = try Connection("\(path)/database.db")
} catch {
    db = nil
    print ("Unable to open database")
}

Upvotes: 1

Views: 1117

Answers (1)

Rob
Rob

Reputation: 437552

In terms of where this file should go, I would suggest the “application support directory”. See File System Programming Guide: Where You Should Put Your App’s Files, which says:

  • Put user data in Documents/. User data generally includes any files you might want to expose to the user—anything you might want the user to create, import, delete or edit. For a drawing app, user data includes any graphic files the user might create. For a text editor, it includes the text files. Video and audio apps may even include files that the user has downloaded to watch or listen to later.

  • Put app-created support files in the Library/Application support/ directory. In general, this directory includes files that the app uses to run but that should remain hidden from the user. This directory can also include data files, configuration files, templates and modified versions of resources loaded from the app bundle.

Also see the iOS Storage Best Practices video.

The above is for iOS. If inquiring about macOS, see File System Programming Guide: The Library Directory Stores App-Specific Files.

But regardless of the OS, the technique for referencing the application support directory is largely the same:

do {
    let fileURL = try FileManager.default
        .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        .appendingPathComponent("database.db")

    db = try Connection(fileURL.path)
} catch {
    db = nil
    print("Unable to open database: \(error)")
}

Upvotes: 1

Related Questions