2

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..!

Gwendal Roué
  • 3,949
  • 15
  • 34
  • What is `Connection`? Show how it attempts to open the database file. – rmaddy Jan 10 '16 at 05:18
  • @rmaddy - Actually it's been told that, if the connection won't find the file. It will attempt to create the file. Problem is it does not create it. –  Jan 10 '16 at 05:21
  • 1
    You need to specify the full path to the file, not just the filename. – rmaddy Jan 10 '16 at 05:25
  • @rmaddy - How do I mention the full path? –  Jan 10 '16 at 05:26

2 Answers2

4

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")
Gwendal Roué
  • 3,949
  • 15
  • 34
1

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")
Muffin Man
  • 41
  • 3