我是 ios 开发的新手。
我关注这个migration example使用预先填充的数据库并稍微更改代码
这是我在 AppDelegate -> func application
上使用的最终代码
let defaultPath = Realm.Configuration.defaultConfiguration.path!
let path = NSBundle.mainBundle().pathForResource("default", ofType: "realm")
if let bundledPath = path {
print("use pre-populated database")
do {
try NSFileManager.defaultManager().removeItemAtPath(defaultPath)
try NSFileManager.defaultManager().copyItemAtPath(bundledPath, toPath: defaultPath)
} catch {
print("remove")
print(error)
}
}
我正在真实设备中对此进行测试。
它可以工作,但根据代码逻辑,它总是会被重置为预填充的数据库。已验证:应用重启后数据会重置。
我尝试使用 moveItemAtPath
而不是 copyItemAtPath
。权限错误
我试图在复制后删除预填充的数据库文件。权限错误
我尝试使用预先填充的数据库文件作为 Realm 默认配置路径。也出现错误。
最佳答案
在 Swift 3.0 中,试试这个:
let bundlePath = Bundle.main.path(forResource: "default", ofType: "realm")
let destPath = Realm.Configuration.defaultConfiguration.fileURL?.path
let fileManager = FileManager.default
if fileManager.fileExists(atPath: destPath!) {
//File exist, do nothing
//print(fileManager.fileExists(atPath: destPath!))
} else {
do {
//Copy file from bundle to Realm default path
try fileManager.copyItem(atPath: bundlePath!, toPath: destPath!)
} catch {
print("\n",error)
}
}
关于Swift Realm,以正确的方式加载预填充的数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36638323/