2017-09-07 56 views
0

我想用FMDB打開現有的數據庫。數據庫應該是一個sqlite數據庫,其結尾爲.db使用FMDB在Swift中打開數據庫

我的代碼是: 靜態設共享:DBManager = DBManager()

let databaseFileName = "/mydb.db" 

var pathToDatabase: String! 

var pathNSURL: NSURL! 

var database: FMDatabase! 


override init() { 
    super.init() 

    let documentsDirectory = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString) as String 

    let zwerg = documentsDirectory + databaseFileName 

    let pathNSURL = NSURL(fileURLWithPath: zwerg) 

    let pathString = documentsDirectory + databaseFileName 

    pathToDatabase = pathNSURL.path 
    print(pathToDatabase) 
} 


func firstQuestion() -> Bool { 
    if openDatabase(){ 
     let query = "SELECT * FROM movie" 

     do { 
      let result = try database.executeQuery(query, values: nil) 
      print(result) 
     } 
     catch { 
      print(error.localizedDescription) 
     } 
     database.close() 
     return true 
    } 
    return false 
} 

func openDatabase() -> Bool { 
    if database == nil { 
     print(FileManager.default.fileExists(atPath: pathToDatabase)) 
     if FileManager.default.fileExists(atPath: pathToDatabase) { 
      print("Database set new path -> File exists") 
      database = FMDatabase(path: pathToDatabase) 
     } 
    } 

    if database != nil { 
     print("Database != nil") 
     if database.open() { 
      print("Database is open in != nil") 
      return true 
     } 
    } 

    return false 
} 

林從VC調用方法firstQuestion():

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 

    print(DBManager.shared.firstQuestion()) 
} 

我的問題是,fileExists-方法總是返回false。該文件名是正確的。這是我的第一個快速的數據庫項目,所以也許我犯了一個愚蠢的錯誤......任何建議?

感謝您的幫助!

回答

0
let fileManager = FileManager.default 
let docURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first! 

let databaseURL = docURL.appendingPathComponent("databaseNaeme.db") 

和初始化數據庫:

database = FMDatabase(path: databaseURL.absoluteString) 
+0

這是路徑:文件:///用戶/ OverBurned /庫/開發商/ CoreSimulator /設備/ B5EAE004-A036-4BD5-A692-C25EF3875D25/data/Containers/Data/Application/3BC1CBA7-48E1-4A17-A456-108667E7F773/Documents/mydb.db但它不是解決方案感謝您的第二個解決方案 – OverBurned

+0

我收到此錯誤消息:致命錯誤:意外地發現零解包an可選值 – OverBurned

+0

嘗試更新,它適用於我 – Alex