Monday, 1 May 2017

Database in Swift Using FMDB

Database in Swift Using FMDB




Checking Out the FMDB Source Code

In order to use FMDB, the source files for the wrapper will need to be added to the project. The source code for FMDB is stored on the GitHub source code repository and can be downloaded directly onto your development system from within Xcode (a process referred to as checking out). Begin by selecting the Xcode Source Control -> Check Out… menu option to display the Check Out dialog:
Adding the FMDB Git repository to an Xcode project
















In the dialog, enter the following GitHub URL into the repository location field and click on Next:


https://github.com/ccgus/fmdb.git


When the list of branches appears in the dialog, select master and click on Next once again. Choose a location on your local file system into which the files are to be checked out before clicking on the Check Out button. Xcode will check out the files and save them at the designated location. A new Xcode project window will also open containing the FMDB source files. Within the project navigator panel, unfold the fmdb -> Source -> fmdb folder to list the source code files (highlighted in Figure ) for the FMDB wrapper.

Adding the FMDB source files to the project


Shift-click on the first and last of the files in the fmdb folder to select all of the .h and .m files in the navigator panel and drag and drop them onto the Database project folder in the Xcode window containing the Database project. On the options panel click on the Finish button. Since these files are written in Objective-C rather than Swift, Xcode will offer to configure and add an Objective-C bridging header file as shown in Figure :


Generating the Objective-C bridging header



Click on the option to add the bridging file. Once added, it will appear in the project navigator panel with the name swiftDemo-Bridging-Header.h. Select this file and edit it to add a single line to import the FMDB.h file:


#import "FMDB.h"


With the project fully configured to support SQLite from within Swift application projects, the remainder of the project may now be completed.

Add This PCH file in Build Settings of Application target :






Designing the User Interface


The next step in developing our example SQLite iOS application involves the design of the user interface. Begin by selecting the Main.storyboard file to edit the user interface and drag and drop components from the Object Library (View -> Utilities -> Show Object Library) onto the view canvas and edit properties so that the layout appears as illustrated in Figure :

The user interface for the SQLite example app project


Coding In ViewController :


import UIKit

class ViewController: UIViewController {

    
    @IBOutlet weak var name: UITextField!
    @IBOutlet weak var address: UITextField!
    @IBOutlet weak var phone: UITextField!
    @IBOutlet weak var status: UILabel!
    
    var databasePath = String()
    
    override func viewDidLoad() {
        super.viewDidLoad()
       
        let filemgr = FileManager.default
        let dirPaths = filemgr.urls(for: .documentDirectory,
                                    in: .userDomainMask)
        
        databasePath = dirPaths[0].appendingPathComponent("contacts.db").path
        
        if !filemgr.fileExists(atPath: databasePath as String) {
            
            let contactDB = FMDatabase(path: databasePath as String)
            
            if contactDB == nil {
                print("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))! {
                    print("Error: \(contactDB?.lastErrorMessage())")
                }
                contactDB?.close()
            } else {
                print("Error: \(contactDB?.lastErrorMessage())")
            }
        }
    }

    @IBAction func saveData(_ sender: AnyObject) {
        
        let contactDB = FMDatabase(path: databasePath as String)
        
        if (contactDB?.open())! {
            
            let insertSQL = "INSERT INTO CONTACTS (name, address, phone) VALUES ('\(name.text!)', '\(address.text!)', '\(phone.text!)')"
            
            let result = contactDB?.executeUpdate(insertSQL,
                                                  withArgumentsIn: nil)
            
            if !result! {
                status.text = "Failed to add contact"
                print("Error: \(contactDB?.lastErrorMessage())")
            } else {
                status.text = "Contact Added"
                name.text = ""
                address.text = ""
                phone.text = ""
            }
        } else {
            print("Error: \(contactDB?.lastErrorMessage())")
        }
        
        
    }
    
    @IBAction func findContact(_ sender: AnyObject) {
        
        
        let contactDB = FMDatabase(path: databasePath as String)
        
        if (contactDB?.open())! {
            let querySQL = "SELECT address, phone FROM CONTACTS WHERE name = '\(name.text!)'"
            
            let results:FMResultSet? = contactDB?.executeQuery(querySQL,
                                                               withArgumentsIn: nil)
            
            if results?.next() == true {
                address.text = results?.string(forColumn: "address")
                phone.text = results?.string(forColumn: "phone")
                status.text = "Record Found"
            } else {
                status.text = "Record not found"
                address.text = ""
                phone.text = ""
            }
            contactDB?.close()
        } else {
            print("Error: \(contactDB?.lastErrorMessage())")
        }
        
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}







No comments:

Post a Comment