I\'m creating a simple chat app to learn Swift and Firebase. I have a query that checks for a chat room\'s messages to load into a tableView. The query returns a snapshot bu
I do not think you want a ChildAdded handler, so I go with a observeSingleEvent example since you want to query data from the database at that time without triggers. When you use a observeSingleEvent, it is important to keep the database in sync. I would recommend using the code below:
query.keepSynched(true) //keeps data in sync with database, if you have data persistince on in your appDelegate
query.observeSingleEvent(of: .value, with: { (snapshot) in //notice the changed here
print(snapshot)
//Since you want to loop again because there could be multiple
//messages in that chatroom which all have a unique ID, do this loop:
let enumerator = snapshot.children
while let rest = enumerator.nextObject() as? FIRDataSnapshot {
//this is 1 single message here
let values = rest.value as? NSDictionary
for (key, value) in values{
print("Key: \(key), value: \(value)")
}
//lets say you want to check if there is a value with a key named "text":
let textUser = values?["text"] as? String ?? "No text found"
//providing a default value if there is no text. You could leave it empty, than it is nil (not recommend)
//Not only is this a lot more readable, I do not use force unwrapping so your app
//cannot cause an exception.
//Get more values from the dictionary as I did with textUser
//Initialize message than here. You will see you do not need to force unwrap anything :D
}
}
})