2017-07-02 33 views
1

我最近啓動了一個iOS項目,需要與獨立數據庫一起工作,這些數據庫在更新時將從互聯網下載。這是我的第一個iOS項目,所以我正在設計下載機制之前嘗試使用功能。如何使用iOS中的現有SQLite數據庫?

我選擇了SQLite包裝SWLite.swifthttps://github.com/stephencelis/SQLite.swift),並準備好我的查詢和表視圖。但我無法連接到數據庫。我已經嘗試過幾乎所有其他問題/答案,絕對沒有成功。

例如,我放棄了SQLite數據庫到Assets.xcassets並試圖let path = Bundle.main.path(forResource: "myDb", ofType: "db")!,和應用程序崩潰(如我nil回來 - 大概是因爲路徑無法找到)。同樣,我嘗試了別人的建議,包括在我的Mac上創建一個文件夾,將文件放入其中,將.bundle添加到文件夾名稱,然後再將其放入資產... nil

有人可以提醒嗎?我看過Apple Docs,並且找不到我要找的東西 - 再次,這是我第一次,所以也許我做錯了。

回答

1

你不能直接從手機上的軟件包sqlite文件中讀取數據。您必須先將其複製到「文檔」文件夾中,然後從此處開始閱讀。這隻需要做一次。要移動它,

let path = Bundle.main.path(forResource: "DBName", ofType: "sqlite") 
do{ 
    try fileManger.copyItem(atPath: path!, toPath: dbPath) 
}catch let error as NSError { 
    print("error occurred, here are the details:\n \(error)") 
} 

然後進行連接時,可以使用

let doumentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString 
let dbPath = doumentDirectoryPath.appendingPathComponent("DBName.sqlite") 
+0

@ The48Percent DBPATH是文檔文件夾下你的SQLite文件的字符串格式路徑。你可以使用你的SQLite庫從那裏讀取文件。 –

+0

你可以給一個'dbPath'應該是什麼樣的例子嗎?應用程序在帶有致命錯誤的try語句中崩潰:意外地在解包可選值時發現nil。代碼是你的建議的混合:'嘗試fileManager.copyItem(atPath:path !, toPath:「myDb.sqlite」)' – The48Percent

+0

@ The48Percent在我的第二個例子中使用'dbPath'。 –

-1

首先,你永遠不希望有你的分貝其他地方,除了在你的文件夾。

這裏是做SQLite.Swift過程: -

// this is the path where your DB should be 

let path = NSSearchPathForDirectoriesInDomains(
.documentDirectory, .userDomainMask, true 
).first! 


// this is how you create a DB with a table:- 

    do { 
       let db_name = "my_db" 
       let db = try Connection("\(path)" + "/" + db_name! + ".sqlite3") 
       try db.key("12345") // if db is encrypted with SQLCipher 

       do { 
        try db.run(mastertableName.create(ifNotExists: true) { t in 

         t.column(database_name) 
         t.column(email, unique: true) 
         t.column(date_created) 
         t.column(device_info) 
        }) 
       } 
       catch { 

        print("Creating Master Table Failed!") 
       } 

只是做一個連接,它會創建一個數據庫的你,如果不存在的話!

讀取DB: -

do { 
     let db_name = "my_db" 
     let db = try Connection("\(path)" + "/" + db_name! + ".sqlite3") 
     try db.key("12345") 

    // db is now open... do your stuff.. 
} 

catch { 
print("opening the db failed!") 
} 
相關問題