如何在更新iOS应用程序时保存用户详细信息



我有两个sqlite数据库,即workout5.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"
}
}

在安装时,我会检查文件是否存在。但每次我更新应用程序时,数据库都会被替换。如何解决这个问题?

只有在卸载应用程序时,文档目录才会被删除。检查路径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)")
}
}

最新更新