RealmSwift downgrade migration

Viewed 263

Is it possible to detect the user is installing an app version with an older db schema version? (downgrading the app version basically)

Want to know if it is possible to detect and delete the current db file so that the app can still recover from it instead of just crashing.

It is an odd scenario but it is happening (some beta testers and such).

1 Answers

Yes, you have access to the old schema version in the migrationBlock of Realm.Configuration, so just check whether the oldSchemaVersion stored on the device is actually higher than the one your current app version has and if so, delete all Realm files using Realm.deleteFiles(for:).

let currentSchemaVersion = 1
let config = Realm.Configuration(
    schemaVersion: currentSchemaVersion,

    migrationBlock: { migration, oldSchemaVersion in
        if (oldSchemaVersion > currentSchemaVersion) {
            Realm.deleteFiles(for: Realm.Configuration.defaultConfiguration)
        }
    }
)

// Then set the config and create your `Realm` instance
Realm.Configuration.defaultConfiguration = config
let realm = try! Realm()
Related