sqlite - How to bundle a pre populated database in swift -


i know there many related posts notice none of them explain way it, says documentation, looked seems have lack of information on bringing pre populated database swift

i have old database .db more 60k lines 3 columns want bring swift sqlite app using fmdb wrapper, app working in iphone, tried drag contacts.db app can not access it. app when run in device start new database.

i copied database supporting files folder , tried in app folder well, not access neither

is there alredy did , willing show me how it?

in summary, looking insert contacts.db app (bundle) can access in device not in simulator. don't need add delete or edit contact.db in device, database loaded information needed, user search , able display results.

class viewcontroller: uiviewcontroller {  @iboutlet weak var name: uitextfield! @iboutlet weak var address: uitextfield!  var databasepath = nsstring()      override func viewdidload() {     super.viewdidload()      if let resourceurl = nsbundle.mainbundle().urlforresource("contacts", withextension: "db") {         if nsfilemanager.defaultmanager().fileexistsatpath(resourceurl.path!)      }     let filemgr = nsfilemanager.defaultmanager()     let dirpaths =     nssearchpathfordirectoriesindomains(.documentdirectory,             .userdomainmask, true)      let docsdir = dirpaths[0] as! string      databasepath = docsdir.stringbyappendingpathcomponent(                     "contacts.db")      if !filemgr.fileexistsatpath(databasepath string) {          let contactdb = fmdatabase(path: databasepath string)          if contactdb == nil {             println("error: \(contactdb.lasterrormessage())")         }          if contactdb.open() {             let sql_stmt = "create table if not exists contacts (id integer primary key autoincrement, name text, address text, phone text)"             if !contactdb.executestatements(sql_stmt) {                 println("error: \(contactdb.lasterrormessage())")             }             contactdb.close()         } else {             println("error: \(contactdb.lasterrormessage())")         }     }  } 

swift 2 example

a few assumptions:

  1. you have added libsqlite3.tbd project correctly.
  2. you have added sqlite database project correctly.
  3. you have copied required fmdb files project correctly.
  4. you have viewcontroller called viewcontroller.swift

in xcode open viewcontroller.swift file , find following code:

 override func viewdidload() {      super.viewdidload()      // additional setup after loading view, typically nib. 

add following code below comment , please remember change name of database in lines 4 & 5.

     // start of database copy bundle app document directory      let filemanager = nsfilemanager.defaultmanager()      let documentspath = nsurl(fileurlwithpath: nssearchpathfordirectoriesindomains(.documentdirectory, .userdomainmask, true)[0])      let destinationsqliteurl = documentspath.urlbyappendingpathcomponent("sqlite.db")      let sourcesqliteurl = nsbundle.mainbundle().urlforresource("sqlite", withextension: "db")       if !filemanager.fileexistsatpath(destinationsqliteurl.path!) {          // var error:nserror? = nil          {              try filemanager.copyitematurl(sourcesqliteurl!, tourl: destinationsqliteurl)              print("copied")              print(destinationsqliteurl.path)          } catch let error nserror {              print("unable create database \(error.debugdescription)")          }      }        // let's print path database on mac      // can go database in finder.      print(documentspath)       let db = fmdatabase(path: destinationsqliteurl.path)      // let's open database     if !db.open() {         print("unable open database")         return     }      // let's run sql fmdb documents make sure     // working expected.       if !db.executeupdate("create table test(x text, y text, z text)", withargumentsinarray: nil) {         print("create table failed: \(db.lasterrormessage())")     }      if !db.executeupdate("insert test (x, y, z) values (?, ?, ?)", withargumentsinarray: ["a", "b", "c"]) {         print("insert 1 table failed: \(db.lasterrormessage())")     }      if !db.executeupdate("insert test (x, y, z) values (?, ?, ?)", withargumentsinarray: ["e", "f", "g"]) {         print("insert 2 table failed: \(db.lasterrormessage())")     }      if let rs = db.executequery("select x, y, z test", withargumentsinarray: nil) {         while rs.next() {             let x = rs.stringforcolumn("x")             let y = rs.stringforcolumn("y")             let z = rs.stringforcolumn("z")             print("x = \(x); y = \(y); z = \(z)")         }     } else {         print("select failed: \(db.lasterrormessage())")     }      db.close() 

you should able run project , have database copied.

previous answer in case helps someone

the documentation fmdb pretty helpful on topic. using example there, code below should work assuming following things:

  1. you using swift 1.2 or later.
  2. you have added fmdb project.
  3. an sqlite database called contacts.db added project.
  4. in build phases, link binary libraries have added libsqlite3.dylib.

    // //  viewcontroller.swift //  import uikit  class viewcontroller: uiviewcontroller {      @iboutlet weak var name: uitextfield!     @iboutlet weak var address: uitextfield!      override func viewdidload() {         super.viewdidload()         // additional setup after loading view, typically nib.         let filemgr = nsfilemanager.defaultmanager()         let documentsfolder = nssearchpathfordirectoriesindomains(.documentdirectory, .userdomainmask, true)[0] as! string         let path = documentsfolder.stringbyappendingpathcomponent("contacts.db")         let database = fmdatabase(path: path)          if !database.open() {             println("unable open database")             return         }          if !database.executeupdate("create table test(x text, y text, z text)", withargumentsinarray: nil) {             println("create table failed: \(database.lasterrormessage())")         }          if !database.executeupdate("insert test (x, y, z) values (?, ?, ?)", withargumentsinarray: ["a", "b", "c"]) {             println("insert 1 table failed: \(database.lasterrormessage())")         }          if !database.executeupdate("insert test (x, y, z) values (?, ?, ?)", withargumentsinarray: ["e", "f", "g"]) {             println("insert 2 table failed: \(database.lasterrormessage())")         }          if let rs = database.executequery("select x, y, z test", withargumentsinarray: nil) {             while rs.next() {                 let x = rs.stringforcolumn("x")                 let y = rs.stringforcolumn("y")                 let z = rs.stringforcolumn("z")                 println("x = \(x); y = \(y); z = \(z)")             }         } else {             println("select failed: \(database.lasterrormessage())")         }          database.close()      }      override func didreceivememorywarning() {         super.didreceivememorywarning()         // dispose of resources can recreated.     } } 

to test, use build , run button , should see run simulator , following results in xcode's console:

x = a; y = b; z = c x = e; y = f; z = g  

to show console, type shift + cmd +r or go view -> debug area -> activate console