Swift Realm,以正确的方式加载预填充的数据库?

标签 swift realm

我是 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/

相关文章:

ios - SwiftUI 的 minimumFontScale 等价物是多少?

ios - Xcode 经常链接失败

.net - 无法使用 .net sdk 在 Realm 中离线工作

encryption - 带 Realm 的 Electron 。 <未启用加密>

ios - 当 UITextField 成为第一响应者时禁用 UIScrollView 滚动

swift - Xcode 8.2.1 不显示自动完成的文档描述

swift - 不能使用单例类返回其属性

swift - Realm 数据不会显示在物理设备上

java - 为字段名称维护单独常量的替代方法

ios - XCTest 中的 "Cannot modify managed RLMArray outside of a write transaction."