Does Realm Swift have a way to safely delete and create a new encrypted Realm file with a new key (but with the same name)?
My use case: when a user exits my application, I delete the encrypted .realm file, as the encryption key will also be deleted:
static func deleteRealm() { let configuration = Realm.Configuration() let path = NSURL.fileURLWithPath(configuration.path!) .URLByDeletingLastPathComponent? .URLByAppendingPathComponent("encrypted.realm") .path! if NSFileManager.defaultManager().fileExistsAtPath(path) {
(Unfortunately, calling realm.deleteAll() will not be sufficient, as there is a new key)
But when another user logs in immediately after logging out, and I try to reinitialize the encrypted Realm database with a new key, for example:
static func intializeRealm() -> Realm! { let realmKey = generateSecureRealmKey() var configuration = Realm.Configuration() configuration.path = RealmDB.getRealmPath() configuration.encryptionKey = NSData(bytes: realmKey, length: realmKey.count) return try! Realm(configuration: configuration) }
I get this exception:
*** Terminating app due to uncaught exception 'RLMException', reason: 'Realm at path '****/encrypted.realm' already opened with different encryption key'
It seems that the old configuration cache is still in use (as the file name is the same), although the scope file has been deleted.
The autoreleasepool encryption application for Realm Swift uses autoreleasepool to get around this, but this is not possible for a larger application. Or that? Should I surround all areas of use with autoreleasepool ?
source share