【问题标题】:How to migrate Realm DB to shared(AppGroup) Realm DB in Swift?如何在 Swift 中将 Realm DB 迁移到共享(AppGroup)Realm DB?
【发布时间】:2020-05-31 17:44:59
【问题描述】:

所以我有一个使用 Realm 数据库的 iOS 应用程序,并且我一直在使用 SiriKit 实现新的东西,所以现在我正在使用适用于 NSUserDefault 的应用程序组。

但是现在如何将作为默认位置的 Realm 数据库迁移到共享文件夹,以便 Siri 扩展可以访问这些值?

这是我将用于在扩展中读取领域的代码

   let fileURL = FileManager.default
        .containerURL(forSecurityApplicationGroupIdentifier: "group.com.x")!
        .appendingPathComponent("default.realm")
    let config = Realm.Configuration(
        fileURL: fileURL,
        objectTypes: [x1.self, x2.self, EquipmentConsumptionDay.self])
    _ = try! Realm(configuration: config)

【问题讨论】:

  • 您能找到解决方案吗?
  • 是的....让我看看代码

标签: swift realm dbmigrate


【解决方案1】:

解决方案很简单,只需将领域文件复制到新位置即可。

// Migrate now the DATABASE realm
// Copy the file from the default location to the new real location
let fileManager = FileManager.default
let originalPath = Realm.Configuration.defaultConfiguration.fileURL!
let appGroupURL = FileManager.default
    .containerURL(forSecurityApplicationGroupIdentifier: "group.com.xx.siri")!
    .appendingPathComponent("default.realm")
do{
    try _ = fileManager.replaceItemAt(appGroupURL, withItemAt: originalPath)
}
catch{
    print("Error info: \(error)")
}

别忘了做系统迁移,所以这段代码只运行一次

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多