最近新增在应用程序和扩展之间共享Realm数据功能,我对此感到非常兴奋。文档详细介绍了如何将默认的Realm设置为应用程序组目录,并且我已经实现了这一步骤。
以下是我遇到的问题 - 在应用程序组中,传输旧数据库到新位置的最佳方法是什么?
最近新增在应用程序和扩展之间共享Realm数据功能,我对此感到非常兴奋。文档详细介绍了如何将默认的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)
var config = Realm.Configuration()
config.fileURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupIdentifier)!.appendingPathComponent(dbFilename)
Realm.Configuration.defaultConfiguration = config