ios - 在应用程序生命周期的中间将本地 Realm 转换为同步 Realm (在 Swift 中)

标签 ios swift realm realm-cloud

我的应用程序将具有称为多设备同步的付费功能。我想使用 Realm Cloud - 基于查询的同步来实现该功能。

我知道如何将本地 Realm 转换为同步 Realm 感谢 this thread .

但这是基于用户从应用程序开始同步他们的 Realm 的场景 - 在打开他们的非同步本地 Realm 之前。这对我不起作用,因为我的用户将在他们付费后开始同步。

因此,我必须在应用程序生命周期的中间转换他们的本地 Realm,而此时本地 Realm 已经打开。

我的问题在这里。当我尝试将本地 Realm 转换为同步 Realm 时,应用程序崩溃并显示以下消息:

Realm at path ‘…’ already opened with different read permissions.

我试图找到一种方法在转换之前关闭本地 Realm,但 Realm cocoa 不允许我以编程方式关闭 Realm。

这是我将本地 Realm 转换为同步 Realm 的代码。

func copyLocalRealmToSyncedRealm(user: RLMSyncUser) {

    let localConfig = RLMRealmConfiguration()
    localConfig.fileURL = Realm.Configuration.defaultConfiguration.fileURL
    localConfig.dynamic = true
    localConfig.readOnly = true

    // crashes here
    let localRealm = try! RLMRealm(configuration: localConfig)

    let syncConfig = RLMRealmConfiguration()
    syncConfig.syncConfiguration = RLMSyncConfiguration(user: user,
                                                        realmURL: realmURL,
                                                        isPartial: true,
                                                        urlPrefix: nil,
                                                        stopPolicy: .liveIndefinitely,
                                                        enableSSLValidation: true,
                                                        certificatePath: nil)
    syncConfig.customSchema = localRealm.schema

    let syncRealm = try! RLMRealm(configuration: syncConfig)
    syncRealm.schema = syncConfig.customSchema!
    try! syncRealm.transaction {
        let objectSchema = syncConfig.customSchema!.objectSchema
        for schema in objectSchema {
            let allObjects = localRealm.allObjects(schema.className)
            for i in 0..<allObjects.count {
                let object = allObjects[i]
                RLMCreateObjectInRealmWithValue(syncRealm, schema.className, object, true)
            }
        }
    }
}

任何帮助将不胜感激。 谢谢。

最佳答案

我复制了本地 Realm 文件并使用 RLMRealmConfiguration 打开了副本。之后,只需删除这两个文件。这不是最好的解决方案,但它有效

关于ios - 在应用程序生命周期的中间将本地 Realm 转换为同步 Realm (在 Swift 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56438304/

相关文章:

ios - 设置多个 UIViewController 的最合乎逻辑的方法是什么?

ios - 等同于 Realm 中的 attributesByName 核心数据方法/获取 RLMObject 的属性/属性

ios - Iphone 启动画面永远不会消失

ios - 应用商店中的应用大小是上传应用大小的 7 倍

ios - 更新应用程序后 UILocalNotification 自定义声音无法正常工作

ios - Xcode 8.1 和 unwind segues 有问题

android - 从 Realm 迁移到 Sqlite

react-native - Realm 与 React Native 0.29 兼容吗?

ios - 在保持滚动位置的同时对所有 UITableViewCells 的高度变化进行动画处理

ios - 解析 JSON 文件(本地存储),从而在 swift 中创建对象数组