Realm Swift: retrieve user, object not returned wh

2019-09-15 03:08发布

问题:

I use Realm to store user information. When I launch the app, I look into the Realm database to see if there is a user object (to determine if the user is logged in or logged out). Here's 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)
        //prints 0
        print("user:", u.count)
    }catch let e as NSError{
        print("failed to initate realm /", e)
    }

    return true
}

I can see from Realm Browser that the user is in the database. But I can't get it. I'm probably initiating Realm the wrong way but I can't figure it out. Any idea?


UPDATE: Here's the code I call to save the user when registering or logging:

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)
         }
     }
}
标签: ios swift realm