Mathias Mathias - 3 years ago 172
iOS Question

Firebase iOS - access user object from other view controller

I have two view controllers, one where the user register (email, password ) himself into the app, and an other one where he can choose a username, I manage to get the first view controller working with Firebase this means that my user is authenticated and I manage to enter his email adress into the realtime database, but I have problem updating the username he choose to the database, I tried this :

self.ref.child("Users").child(user.uid).setValue(["username": usernameTextfield.text])

I believe this is not working because my viewcontroller doesn't know the object user. Can someone tell me how to do it. Thanks

Answer Source

If you created a user object in the context of your first view controller, then you're right, you won't be able to access this from the second view controller.

However you can recreate this user object on the second view controller by calling Auth.auth().currentUser, shown below:

if let user = Auth.auth().currentUser {
    // use the user object here
    self.ref.child("Users").child(user.uid).setValue(["username": usernameTextfield.text])
} else {
    print("no user is logged in")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download