我有两个sqlite数据库,即execution5.sqlite3和custom_ios.sqlite3。我将两个数据库都复制到安装目录中的用户目录中
if !fileManager.fileExists(atPath: dbPath) {
let fromPath: String? = Bundle.main.resourcePath?.stringByAppendingPathComponent(fileName as String)
var error : NSError?
do {
try fileManager.copyItem(atPath: fromPath!, toPath: dbPath)
}
catch let error1 as NSError {
error = error1
}
let alert: UIAlertView = UIAlertView()
if (error != nil) {
alert.title = "Error Occured"
alert.message = error?.localizedDescription
}
else {
alert.title = "Successfully Copy"
alert.message = "Your database copy successfully"
}
}
在安装时,我检查文件是否存在。但是每次我更新应用程序时,数据库都会被替换。如何解决这个问题?
答案 0 :(得分:1)
仅在卸载应用程序时,文档目录将被删除。检查路径isReadableFile(atPath:)
上是否存在可读文件。
这是示例代码:
let DBNAME = "myDB.sqlite"
let yourOriginalDatabasePath = URL(fileURLWithPath: Bundle.main.resourcePath ?? "").appendingPathComponent(DBNAME)
let pathsToDocuments = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let dbPath = URL(fileURLWithPath: pathsToDocuments[0]).appendingPathComponent(DBNAME)
print("dataBasebPath: \(dbPath.absoluteString)")
let isFileExist = FileManager.default.fileExists(atPath: dbPath.absoluteString)
let isReadableFileExist = FileManager.default.isReadableFile(atPath: dbPath.absoluteString)
if !isReadableFileExist && !isFileExist {
print("[DB] Copying DB to Documents Folder")
do {
try FileManager.default.copyItem(at: yourOriginalDatabasePath, to: dbPath)
} catch {
print("Fail to copy database from \(yourOriginalDatabasePath) to \(dbPath). Error: \(error)")
}
}