如何将领域数据库迁移到应用程序组?

How to migrate a realm database to an app group?

对于最近在应用程序和扩展程序之间共享 Realm 数据感到非常兴奋。该文档详细说明了如何将默认领域设置为应用程序组目录,我已经做到了。

这就是我坚持的问题 -- 将旧数据库转移到应用程序组中的新位置的最佳方法是什么?

根据@segiddins 的评论,我决定使用 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)

希望这会对其他人有所帮助 reader。

https://github.com/realm/realm-cocoa/issues/4490 中所述,您可以使用以下代码设置应用程序组路径,并使用文件管理器移动现有数据库,如上所述。

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