Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing and querying through an SQLite database in Swift - iOS

I'm making an app that makes use of a big database with 5 different tables. I want to import that database to the app bundle and be able to query through the tables. The database won't be edited by the user, so adding and removing records is not required.

What would be the best way to add the database in the app?

like image 321
Panos S Avatar asked Oct 13 '14 17:10

Panos S


People also ask

How do I open SQLite database in iOS Swift?

File ▸ New ▸ Project…. Choose the iOS ▸ Application ▸ Single View App template and create a new project. Step 1: First copy . sqlite file from FileManager to application.

How do you access SQLite using iOS mobile application?

Step 1 − Open Xcode -→ Single View Application -→ Let's name is DBSqlite. Step 2 − Let's develop our UI, Open Main. storyboard and add one text field and two buttons as shown below. Step 3 − Create @IBAction for both the buttons and @IBOutlet for text field and name them btnInsert, btnShowData and name respectively.


1 Answers

The process is as follows:

  1. Add the database to your bundle. When you drag it into your project, you can choose to add it to the target that represents your main app. Alternatively, review the target settings, click on "Build Phases" and confirm the database appears in the "Copy Bundle Resources" list.

  2. Use a framework like FMDB to simplify your life. This is written in Objective-C, but works great in Swift, too. What you need to do is:

    • Copy the .h and .m files for FMDB into your project;

    • When prompted to create a "bridging header", do so;

    • Add the following line to your bridging header:

      #import "FMDB.h"
      

    By following those steps, you can use this framework developed in Objective-C into your Swift projects.

  3. You can now write your Swift code, using the FMDB framework. For example, the Swift code to open the database, select columns x, y, and z from a table called test, would look like:

    let path = NSBundle.mainBundle().pathForResource("test", ofType:"sqlite")
    
    let database = FMDatabase(path: path)
    
    if !database.open() {
        print("Unable to open database")
        return
    }
    
    if let rs = database.executeQuery("select * from 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("executeQuery failed: \(database.lastErrorMessage())")
    }
    
    database.close()
    
like image 174
Rob Avatar answered Oct 26 '22 03:10

Rob