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

Jes*_*sse 8 realm swift

我是ios开发的新手.

我按照这个迁移示例来使用预先填充的数据库并稍微更改代码

这是我使用的最终代码 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)
        }
    }
Run Code Online (Sandbox Code Playgroud)

我正在一个真实的设备中测试它.

它可以工作,但根据代码逻辑,它将始终重置为预先填充的数据库.这已经过验证:应用程序重启后数据会重置.

我试过moveItemAtPath而不是copyItemAtPath.权限错误

我试图在复制后删除预先填充的数据库文件.权限错误

我尝试使用预先填充的数据库文件作为域默认配置路径.也发生了错误.

小智 9

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)
        }
    }
Run Code Online (Sandbox Code Playgroud)


TiM*_*TiM 3

是的,你的逻辑是正确的。每次执行此代码时,Documents 目录中的默认 Realm 文件都会被删除,并替换为应用程序包附带的静态副本。这是通过 Realm 示例代码设计完成的,以便演示每次启动应用程序时的迁移过程。

如果您只想发生一次,最简单的方法是事先检查默认路径中是否已存在 Realm 文件,然后仅在该文件不存在时才执行复制。:)

let alreadyExists = NSFileManager.defaultManager().fileExistsAtPath(defaultPath)

if alreadyExists == false && 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)
    }
}
Run Code Online (Sandbox Code Playgroud)