Swift Realm, load the pre-populated database the right way?

风格不统一 提交于 2019-11-29 14:45:59

问题


I'm pretty new to ios development.

I follow this migration example to use pre-populated database and change the code a little bit

here is the final code I use on 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)
        }
    }

I'm testing this in a real device.

It works but according to the code logic, it'll always be reset to the pre-populated database. This is verified: the data is reset after app restart.

I tried moveItemAtPath instead of copyItemAtPath. permission error

I tried to delete the pre-populated database file after copy. permission error

I tried to use the pre-populated database file as the realm default configuration path. error occurs too.


回答1:


Yeah, your logic is correct. Every time this code gets executed, the default Realm file in the Documents directory is deleted and replaced with the static copy that came with the app bundle. This is done by design in the Realm sample code in order to demonstrate the migration process each time the app is launched.

If you only want that to happen one time, the easiest way to do it would be to check beforehand to see if a Realm file already exists at the default path, and then perform the copy only when it isn't already there. :)

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)
    }
}



回答2:


In Swift 3.0, try this:

    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)
        }
    }


来源:https://stackoverflow.com/questions/36638323/swift-realm-load-the-pre-populated-database-the-right-way

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!