How to migrate a realm database to an app group?

半世苍凉 提交于 2019-12-03 12:42:45

问题


Really excited about the recent addition of sharing Realm data between apps and extensions. The documentation details how to set the default realm to the app group directory, I've got that working.

Here's what I'm stuck on -- what's the best way to transfer the old database to the new location in the app group?


回答1:


Based on @segiddins comment, I decided to go with moving the old database to the app group using NSFileManager:

    let fileManager = NSFileManager.defaultManager()

    //Cache original realm path (documents directory)
    let originalDefaultRealmPath = RLMRealm.defaultRealmPath()

    //Generate new realm path based on app group 
    let appGroupURL: NSURL = fileManager.containerURLForSecurityApplicationGroupIdentifier("group.AppGroup")!
    let realmPath = appGroupURL.path!.stringByAppendingPathComponent("default.realm")

    //Moves the realm to the new location if it hasn't been done previously
    if (fileManager.fileExistsAtPath(originalDefaultRealmPath) && !fileManager.fileExistsAtPath(realmPath)) {

        var error: NSError?
        fileManager.moveItemAtPath(originalDefaultRealmPath, toPath: realmPath, error: &error)

        if (error != nil) {
            println(error)
        }
    }

    //Set the realm path to the new directory
    RLMRealm.setDefaultRealmPath(realmPath)



回答2:


Hope this will help other reader.

As discussed in https://github.com/realm/realm-cocoa/issues/4490, you can set app group path with below code and use File Manager to move existing db as mention above.

var config = Realm.Configuration()
config.fileURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupIdentifier)!.appendingPathComponent(dbFilename)
Realm.Configuration.defaultConfiguration = config


来源:https://stackoverflow.com/questions/29996999/how-to-migrate-a-realm-database-to-an-app-group

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