SQLite.swift (Release 0.11.2) sample code is not working

497 views Asked by At

I am trying to use SQLite.swift sample code but it is throwing an error.

First step I have done is to install it using cocoapods and it was successful. Then I have tried to test it in my app delegate where I declare import SQLite and I have added the below code in didFinishLaunchingWithOptions but it is showing an error.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    let db = try Connection("path/to/db.sqlite3")

    let users = Table("users")
    let id = Expression<Int64>("id")
    let name = Expression<String?>("name")
    let email = Expression<String>("email")

    try db.run(users.create { t in
        t.column(id, primaryKey: true)
        t.column(name)
        t.column(email, unique: true)
    })

    return true
}

The error I am getting from this code line (let db = try Connection("path/to/db.sqlite3")) is "Errors thrown from here are not handled"

Is there anyone experiencing the same issue? I am using XCode 8.2.1 and Swift 3.0.

2

There are 2 answers

0
Mark Angelo Hernandez On BEST ANSWER

Thanks to @martin-r for the solution. Here's the updated code. Solution:

do {
        let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]

        let db = try Connection("\(documentsPath)/db.sqlite3")

        let users = Table("users")
        let id = Expression<Int64>("id")
        let name = Expression<String?>("name")
        let email = Expression<String>("email")

        try db.run(users.create { t in
            t.column(id, primaryKey: true)
            t.column(name)
            t.column(email, unique: true)
        })

    } catch {
        // Handle error
    }
1
miho On

Your app needs to know what it should do when there is a runtime error. What you're missing is a do/catch clause or the throws keyword at your function declaration. For more details have a look at chapter "Error Handling" of the the Swift book.