I'm relying on an encrypted realm to store certain data in an app written in Swift. Sometimes I face a situation where I delete a given realm and create a new one to ensure that no data will persist between certain states.
I keep track of encryption keys myself, so there is a risk that I unintentionally attempt to decrypt a realm with a wrong encryption key, which raises the following exception:
libc++abi.dylib: terminating with uncaught exception of type realm::RealmFileException: Unable to open a realm at path '/path/to/private.realm': Realm file decryption failed.
Since this means that I have lost the original encryption key, essentially leaving this particular realm useless, I'd like to be able to delete the realm file and start over instead of crashing.
I create the realm as suggested by the docs:
do {
var configuration = Realm.Configuration.defaultConfiguration
configuration.encryptionKey = ...
try Realm(configuration: configuration)
}
catch let error {
}
I've tried this and similar approaches to catch the NSException
and return it to be handled by Swift code, but there doesn't seem to be an straight forward way to achieve this. Is it impossible, or am I approaching this incorrectly?
Your code should work. If the encryption key is wrong, entered the catch block. Then you can delete existing file and re-create Realm. Like the following:
var configuration = Realm.Configuration.defaultConfiguration
configuration.encryptionKey = getKey()
do {
let realm = try Realm(configuration: configuration)
...
}
catch {
try! NSFileManager().removeItemAtURL(configuration.fileURL!)
let realm = try! Realm(configuration: configuration)
...
}
If you cannot catch the wrong encryption error, it might be using old Realm.framework. Please update the latest version of Realm.
It turns out the problem was caused by a bug in Realm, where deleteRealmIfMigrationNeeded = true
when using encryption, caused the exception to be thrown, but impossible to catch.
From my (very helpful) correspondence with kishikawa katsumi:
The problem that unable to catch error is due to
deleteRealmIfMigrationNeeded
is true. It changes code flow unintentionally. It seems Realm's bug. We will fix soon.
For now, the only thing to do in my case is to set deleteRealmIfMigrationNeeded = false
and handle this case manually. I have filed this issue to Realm.
Update: The issue should be resolved with this commit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With