Search code examples
iosswiftsyntaxfmdb

Swift FMDB Code Explanation


I am a beginner to Swift and FMDB, I got the code below from resources in the internet, and tried my best to understand the code. I have put comments below statements stating what I think it is doing. The ones with question marks I do not understand.

class ViewController: UIViewController {
@IBOutlet weak var name: UITextField!
@IBOutlet weak var specialty: UITextField!
//Defines name and specialty as contents of text fields

var dbpath = String()
//defines the database path
func getPath(fileName: String) -> String {

    let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
    //finds document and returns an array of paths
    let fileURL = documentsURL.URLByAppendingPathComponent(fileName)
    print(fileName)
    //finds path to fileName with URLByAppendingPathComponent


    print("File Path Is : \(fileURL)")

    return fileURL.path!
    //returns the fileURL in path format?????
}


//Button "Add Shop" definition
override func viewDidLoad() {
    super.viewDidLoad()

    let dirPaths =
    NSSearchPathForDirectoriesInDomains(.DocumentDirectory,
        .UserDomainMask, true)
    //creates search paths for directories, then ?????

    let docsDir = dirPaths[0] 

    let dbPath: String = getPath("shopdata.db")
    //assigns string "shopdata.db" to dbPath
    let fileManager = NSFileManager.defaultManager()
    //easier access for NSFileManager, returns shared file for the process when called

    if !fileManager.fileExistsAtPath(dbPath as String) {
        //if there is already a database, do the following

        let contactDB = FMDatabase(path: dbPath as String)
        //contact database with path identified in function getPath

        if contactDB == nil {
            print("Error: \(contactDB.lastErrorMessage())")
            //If there is no database
        }

        if contactDB.open() {
            let sql_stmt = "CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, SPECIALTY TEXT, NAME TEXT)"
            if !contactDB.executeStatements(sql_stmt)
                //executes a create table statement as defined above
            {
                print("Error: \(contactDB.lastErrorMessage())")
                //if cannot execute statement, display error from fmdb
            }
            contactDB.close()
                //close connection
        } else {
            print("Error: \(contactDB.lastErrorMessage())")
            //if contact cannot be made, display error from fmdb
        }
    }
}

@IBAction func addShop(sender: AnyObject) {
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

Solution

  • This Function will get the file path of the give fileName from DocumentDirectory and return it back.

    func getPath(fileName: String) -> String {
    
    let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
    //finds document and returns an array of paths
    let fileURL = documentsURL.URLByAppendingPathComponent(fileName)
    print(fileName)
    //finds path to fileName with URLByAppendingPathComponent
    
    
    print("File Path Is : \(fileURL)")
    
    return fileURL.path!
    //returns the fileURL in path format?????
    }
    

    And these line of code is not needed in here at all. This code also get the file path from DocumentDirectory of the application. Which is done in the getPath: function.

     let dirPaths =
        NSSearchPathForDirectoriesInDomains(.DocumentDirectory,
            .UserDomainMask, true)
        //creates search paths for directories, then ?????
    
        let docsDir = dirPaths[0] 
    

    DocumentDirectory is where the application save the database. Sorry for bad English. Hope it helps :)