My app (ios) using realm DB to save data. But, some users feedback that they lose data? they said they used the app for a long time before meeting this issue.
And finally, I meet this trouble last week. I create a directory name RealmFolder in Cache Directory. Config file realm in this directory.
I guess maybe the system auto-clear all files in Cache Directory (not verified yet). I try to research and still can not find a resolution because I can not reappear this bug. Now I have a new folder, new realm URL.
This my code config realm:
class LocalDAO {
static let shareInstance = LocalDAO()
var DBName : String = ""
private var realmUrl : URL{
get {
let cacheUrl = FileManager.default.urls(for: FileManager.SearchPathDirectory.cachesDirectory, in: FileManager.SearchPathDomainMask.userDomainMask)[0]
let url = cacheUrl.appendingPathComponent("RealmFolder").appendingPathComponent(self.DBName)
return url
}
}
var config = Realm.Configuration(
schemaVersion: SCHEMA_VERSION,
migrationBlock: { migration, oldSchemaVersion in
if (oldSchemaVersion < SCHEMA_VERSION) {
}
})
func createRealmDirection(){
let cacheUrl = FileManager.default.urls(for: FileManager.SearchPathDirectory.cachesDirectory, in: FileManager.SearchPathDomainMask.userDomainMask)[0]
let directionName = "RealmFolder"
let path = cacheUrl.appendingPathComponent(directionName)
if !FileManager.default.fileExists(atPath: path.path){
try? FileManager.default.createDirectory(atPath: path.path, withIntermediateDirectories: true, attributes: nil)
}
}
func setDefaultRealmForUser(userId: String) {
self.DBName = "DB_\(userId).realm"
config.fileURL = realmUrl
Realm.Configuration.defaultConfiguration = config
}
}