我試圖在我的物理iPhone中包含預填充的SQLite數據庫(使用FMDB包裝器)。但是,預填充數據庫不包含在構建物理設備中。Swift - 未包含在設備上的預填充SQLite數據庫
請注意,它在IOS模擬器中工作正常,但只適用於一個模擬器設備。
我已經將數據庫包含在Build Binses> Copy Bundled Resources和鏈接庫libsqlite3.dylib下。
我需要添加什麼Swift代碼才能將構建中的數據庫包含到物理設備中?
代碼:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var checkButton: UIButton!
@IBOutlet weak var tests_scroller: UITextView!
var databasePath = NSString()
override func viewDidLoad() {
super.viewDidLoad()
checkButton.setTitle("\u{2610}", forState: .Normal)
checkButton.setTitle("\u{2611}", forState: .Selected)
let filemgr = NSFileManager.defaultManager()
let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let docsDir = dirPaths[0] as! String
databasePath = docsDir.stringByAppendingPathComponent("vmd_db.db")
let myDatabase = FMDatabase(path: databasePath as String)
if myDatabase.open(){
var arrayData:[String] = []
let query_lab_test = "SELECT lab_test FROM lab_test ORDER BY lab_test ASC"
let results_lab_test:FMResultSet? = myDatabase.executeQuery(query_lab_test, withArgumentsInArray: nil)
while results_lab_test?.next() == true {
if let resultString = results_lab_test?.stringForColumn("lab_test"){
arrayData.append(resultString)
}
}
var multiLineString = join("\n", arrayData)
tests_scroller.text = multiLineString
myDatabase.close()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
更新 - XCode中7工作斯威夫特2碼 - 使用FMDB包裝複製到物理設備確定預填充SQLite數據庫:從什麼
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tests_scroller: UITextView!
var databasePath = NSString()
override func viewDidLoad() {
super.viewDidLoad()
let sourcePath = NSBundle.mainBundle().pathForResource("vmd_db", ofType: "db")
let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as String!
let destinationPath = (documentDirectoryPath as NSString).stringByAppendingPathComponent("vmd_db.db")
do {
try NSFileManager().copyItemAtPath(sourcePath!, toPath: destinationPath)
} catch _ {
}
//read it
let myDatabase = FMDatabase(path: destinationPath as String)
if myDatabase.open(){
var arrayData:[String] = []
let query_lab_test = "SELECT lab_test FROM lab_test ORDER BY lab_test ASC"
let results_lab_test:FMResultSet? = myDatabase.executeQuery(query_lab_test, withArgumentsInArray: nil)
while results_lab_test?.next() == true {
if let resultString = results_lab_test?.stringForColumn("lab_test"){
arrayData.append(resultString)
}
}
let multiLineString = arrayData.joinWithSeparator("\n")
tests_scroller.text = multiLineString
myDatabase.close()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
爲什麼我的問題被拒絕? – IlludiumPu36
下來選民留下沒有評論,所以我upvoted反投票。 –