【问题标题】:Converting local Realm to synced Realm in the middle of app life cycle (in Swift)在应用程序生命周期的中间将本地领域转换为同步领域(在 Swift 中)
【发布时间】:2019-06-04 06:17:36
【问题描述】:

我的应用将具有一项称为多设备同步的付费功能。我想用 Realm Cloud - Query Based Sync 来实现这个功能。

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

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

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

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

路径‘...’的领域已经以不同的读取权限打开。

我试图找到一种在转换之前关闭本地 Realm 的方法,但 Realm cocoa 不允许我以编程方式关闭 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)
            }
        }
    }
}

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

【问题讨论】:

  • 你能解决这个问题吗?
  • 不,浪费了几个星期后我放弃了使用领域云平台。我切换到 CloudKit。我切换到 Cloudkit 的另一个原因是领域云的定价。 “10,000 个同时连接”并不意味着 10,000 个实时连接。 1 个注册设备(不是用户)是 1 个连接。用户现在是否正在使用您的应用并不重要。除非用户删除应用程序,否则即使用户终止应用程序,计数仍将保留。我测试了一下,结果吓到我了。
  • 感谢您的更新!您是否使用 IceCream 将您的本地领域与 CloudKit 同步?
  • @mergesort 我试过 IceCream 但很快就放弃了,因为它有同步循环问题。而且我还需要自定义逻辑。

标签: ios swift realm realm-cloud


【解决方案1】:

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

【讨论】:

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