Im using Realm 2.1.1, and been using since the version 0.98.
What is happening is sometimes when the user enter background, after sometime like 1 hour or more, the Realm Database loses all its objects.
Already check it, and im not permforming any saving or retrieve some objects on the background.
I perform a migration to app group on the didFinishLaunchingWithOptions
, because i was using an Widget, that i think that was causing the problem, since it try to access realm from another thread.
The realm database is encrypted, so i don't know if maybe its something from the keychain entering the background.
Heres my code to initialize the RealmDatabase :
class func migrateRealm() {
let config = RLMRealmConfiguration.defaultConfiguration()
config.schemaVersion = realmSchemeVersion()
config.migrationBlock = {(migration:RLMMigration, oldSchemaVersion: UInt64) in }
RLMRealmConfiguration.setDefaultConfiguration(config)
//Cache original realm path (documents directory)
guard let originalDefaultRealmPath = RealmEncrypted.realm().configuration.fileURL?.absoluteString else {
return
}
//Generate new realm path based on app group
let appGroupURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("app")!
let realmPath = appGroupURL.URLByAppendingPathComponent("default.realm")?.path ?? ""
//Moves the realm to the new location if it hasn't been done previously
if (NSFileManager.defaultManager().fileExistsAtPath(originalDefaultRealmPath) && !NSFileManager.defaultManager().fileExistsAtPath(realmPath)) {
do {
try NSFileManager.defaultManager().moveItemAtPath(originalDefaultRealmPath, toPath: realmPath)
//Set the realm path to the new directory
config.fileURL = NSURL(string: realmPath)
RLMRealmConfiguration.setDefaultConfiguration(config)
do {
try NSFileManager.defaultManager().removeItemAtURL(NSURL(string: originalDefaultRealmPath)!)
}
catch let error as NSError {
print("Ooops! Something went wrong deleting : \(error)")
}
}
catch let error as NSError {
print("Ooops! Something went wrong: \(error)")
}
}
else {
config.fileURL = NSURL(string: realmPath)
RLMRealmConfiguration.setDefaultConfiguration(config)
}
}