user5246938
user5246938

Reputation:

Why do I get Unable to Open Database file?

I am a beginner in iOS development and I want to develop a database in my application. However, When I try to create the database it says unable to open database file.

enter image description here

For clarification (https://github.com/stephencelis/SQLite.swift/blob/master/Documentation/Index.md)

enter image description here

My code for the db development is as follow

static func DB(){

        do {
            let db = try Connection("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 {
            print("Dim background error")
        }
}

I trigger this method from app delegate file

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

        AppCommon.DB()

        return true
    }

How to fix this issue? Please help me out, I really need your help..!

Upvotes: 2

Views: 5554

Answers (2)

Muffin Man
Muffin Man

Reputation: 81

Swift 5

Path of Documents directory is now an array of strings

let path = NSSearchPathForDirectoriesInDomains(
                .documentDirectory, .userDomainMask, true)
let db = try Connection("\(path.first ?? "")/db.sqlite3")

Upvotes: 1

Gwendal Rou&#233;
Gwendal Rou&#233;

Reputation: 4044

On iOS, you can't create files where you want. A correct place (among others) is in the documents directory.

Quoting the documentation of the library you are using https://github.com/stephencelis/SQLite.swift/blob/master/Documentation/Index.md#connecting-to-a-database:

On iOS, you can create a writable database in your app’s Documents directory.

let path = NSSearchPathForDirectoriesInDomains(
   .DocumentDirectory, .UserDomainMask, true
).first!

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

Upvotes: 4

Related Questions