AJGronevelt AJGronevelt - 1 month ago 15
iOS Question

iOS Swift: retrieve an entry from the database for the user currently logged in

Guys this is driving me crazy but I cannot work out how to retrieve a value (other than username and user id, which seem easier to get) for the current user from the database.

Ironically, I can set the value as follows and that works just fine:

let databaseRef = FIRDatabase.database().reference()
userID = (FIRAuth.auth()?.currentUser?.uid)! as String

But for the life of me I cannot work out what to put instead of
if I simply want to retrieve the current
value. I thought just using
as for example in

let DesiredValue = databaseRef.child("users").child(userID!).child("TermCond").value as? String

Would suffice, but nothing works. I am confused why retrieving the value should be more difficult than setting it.

Thank you so much for your help.



To "read" a value from Firebase, you need to add a reference listener that gets called every time that value changes.

In your case, that could be something like:

let databaseRef = FIRDatabase.database().reference()
databaseRef.child("users").child(userID!).child("TermCond").observe(FIRDataEventType.value, with: { (snapshot) in
    let desiredValue = snapshot.value as? String

This block of code will get triggered every time your value changes. If you only want to read it once, you can use observeSingleEvent:of:with instead of observe:with.

This is as described in the Firebase documentation: https://firebase.google.com/docs/database/ios/read-and-write

I recommend you read their entire Documentation to get an idea of how Firebase works, as it is very different from traditional databases.

I can also recommend the following tutorial if you'd like to learn a bit more about the Firebase Database and how it works: https://www.raywenderlich.com/139322/firebase-tutorial-getting-started-2