I am saving data in swift, to a realtime firebase database using the following code:
guard let key = dbreference.child(("user-clients")).childByAutoId().key else { return }
let post = ["uid": userID,
"firstname": clientfirstname,
"lastname": clientlastname,
"dateofbirth": clientdateofbirth,
"haircolour": clienthaircolour,
"products": clientproduct]
let childUpdates = ["/user-clients/\(String(describing: user))/\(key)/": post]
dbreference.updateChildValues(childUpdates)
This automatically creates a child ID under the user that is logged in (so is my understanding?) and it works fine as my database is updating correctly.
The problem is - I am trying to read the first name and last name of each person and display in a table view (like a contact card) but I cannot 'pull out' the firstname
and lastname
data.
Here is my code to retrieve the data:
let dbref = Database.database().reference()
let me: String = (Auth.auth().currentUser?.uid)!
let key = dbreference.child(("users")).childByAutoId().key
//Access the databse and retrieve First and Last Names from child
dbref.child("user-clients").queryOrdered(byChild: me).observeSingleEvent(of: DataEventType.value) { (snapshot) in
if snapshot.exists() {
print("exists")
for child in snapshot.children {
let data = child as! DataSnapshot
//print(data.key)
print(data.value!)
if (data as AnyObject).hasChild("firstname") {
print("perfect")
} else {
print("does not exist")
}
if let firstname = snapshot.childSnapshot(forPath:"firstname").value as? String {
print(firstname)
}
if let lastname = snapshot.childSnapshot(forPath:"lastname").value as? String {
print(lastname)
}
}
}
It seems like I am not getting down another level as the console prints out all the contacts under the different autogenerated ID's. My JSON file looks like this:
{
"user-clients" : {
"Optional(\"4WNCGOaiIMTKAa12Pmi26w11hSb2\")" : {
"-M943knUA5JkpMuxygti" : {
"dateofbirth" : "7777",
"firstname" : "john",
"haircolour" : "blue",
"lastname" : "melon",
"products" : "09876543321",
"uid" : "4WNCGOaiIMTKAa12Pmi26w11hSb2"
},
"-M944HmLvM50rEc4qtM3" : {
"dateofbirth" : "12/12/12",
"firstname" : "basil",
"haircolour" : "yellow",
"lastname" : "brush",
"products" : "678990099",
"uid" : "4WNCGOaiIMTKAa12Pmi26w11hSb2"
},
"-M94C9yk7q6mQglQiaoR" : {
"dateofbirth" : "12/12/77",
"firstname" : "Homer",
"haircolour" : "yellow",
"lastname" : "Simpson",
"products" : "123456789",
"uid" : "4WNCGOaiIMTKAa12Pmi26w11hSb2"
},
"-M94CISM865qWAa8nbK-" : {
"dateofbirth" : "12/11/77",
"firstname" : "Marge",
"haircolour" : "Blue",
"lastname" : "Simpson",
"products" : "09876654433",
"uid" : "4WNCGOaiIMTKAa12Pmi26w11hSb2"
}
Any help would be greatly appreciated and I hope the above makes sense. Thanks in advance.