I use Realm to store user information. When I launch the application, I scan the Realm database to see if there is a user object (to determine if the user is logged in or logged out). Here is my code:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let config=Realm.Configuration(
schemaVersion: 2,
migrationBlock: { migration, oldSchemaVersion in
if (oldSchemaVersion<1) || (oldSchemaVersion<2){
migration.enumerateObjects(ofType: User.className()) { oldObject, newObject in
}
}
})
Realm.Configuration.defaultConfiguration=config
do{
let r=try Realm()
print(Realm.Configuration.defaultConfiguration.fileURL!.path)
let u=r.objects(User.self)
print("user:", u.count)
}catch let e as NSError{
print("failed to initate realm /", e)
}
return true
}
I can see from the Realm browser that the user is in the database . But I can’t understand it. I probably initiate Realm wrong, but I can't figure it out. Any idea?
UPDATE : Here is the code that I call to save the user during registration or registration:
DispatchQueue.main.async{
do{
let r=try Realm()
try r.write{
let u=User(id:"id", username:"username")
r.add(u)
}
}catch let e as NSError{
print(e)
}
}
}
source
share