Search code examples
iosswiftsqlitefmdb

Swift Database FMDB Error and Explanation


I am having some trouble compiling this on xcode.

Line 6: " let docsDir = dirPaths[0] as! String" returns an error of "Forced Cast of 'String' to the same type has no effect." What is as! String doing? as it tells me to delete it.

Second question is line 8 where stringByAppendingPathComponent seems to have been removed by swift but after reading some questions on stack, it shows that NSString works with it. How would I implement the NSString change to the code?

The last question I would like to ask is I don't get minority of this code, is there anywhere I could learn such things such as what is "defaultManager" doing after the class NSFileManager or just line 2 and 3 in general.

    let filemgr = NSFileManager.defaultManager()
    let dirPaths =
    NSSearchPathForDirectoriesInDomains(.DocumentDirectory,
        .UserDomainMask, true)

    let docsDir = dirPaths[0] as! String

    let databasePath = docsDir.stringByAppendingPathComponent(
        "shopdata.db")

    if !filemgr.fileExistsAtPath(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, SPECIALTY TEXT, NAME TEXT)"
            if !contactDB.executeStatements(sql_stmt) {
                print("Error: \(contactDB.lastErrorMessage())")
            }
            contactDB.close()
        } else {
            print("Error: \(contactDB.lastErrorMessage())")
        }
    }

Solution

  • Try to use this code the path of file

    func getPath(fileName: String) -> String {
    
            let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
            let fileURL = documentsURL.URLByAppendingPathComponent(fileName)
    
    
             print("File Path Is : \(fileURL)")
    
            return fileURL.path!
        }
    

    And then call this function like this

    let dbPath: String = getPath("shopdata.db")
            let fileManager = NSFileManager.defaultManager()
            if !fileManager.fileExistsAtPath(dbPath) {
    
            // Your remaining Code here
    }
    

    Hope it help :) (Sorry for bad English)