简体   繁体   中英

Converting local Realm to synced Realm in the middle of app life cycle (in Swift)

My app will have a paid feature called multi-devices sync. I would like to implement the feature with Realm Cloud - Query Based Sync.

I know how to convert local Realm to synced Realm thanks to this thread .

But this is based on the scenario that users sync their Realm from the app start - before opening their non-synced local realm. That doesn't work for me because my users will start sync when they paid for it.

Therefore, I have to convert their local Realm in the middle of app life cycle and the local Realm is already opened by that time.

My issue comes in here. When I try to convert local realm to synced realm, app crashes with this message:

Realm at path '…' already opened with different read permissions.

I tried to find a way to close local Realm before converting it, but Realm cocoa does not allow me to close a Realm programmatically.

Here's my code converting local Realm to synced 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)
            }
        }
    }
}

Any help will be appreciated. Thanks.

I made a copy of the local realm file and opened the copy with RLMRealmConfiguration. Afterwards, just delete both files. It is not the best solution, but it works

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM