Reputation: 768
Iv got a search bar that when you type it searches the database for that users username. The code that find the username work, but when i try and read a specific value it crashes. This is the code
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
Database.child("users").queryOrderedByChild("username").queryEqualToValue(searchText).observeSingleEventOfType(.Value, withBlock: { snapshot in
print(snapshot)
print(snapshot.value!["first_name"] as? String)
print(snapshot.value!["last_name"] as? String)
print(snapshot.value!["username"] as? String)
print(snapshot.value!["profile_picture_url"] as? String)
})
}
The results from printing the snapshot are
Snap (users) {
12345UIDEXample = {
"first_name" = Bob;
"last_name" = Someone;
"profile_picture_url" = "exampleurl.com";
username = bobby;
};
}
but when i try access
snapshot.value!["first_name"] as? String
it returns nil and crashes? Why if its clearly showing in the json that its returned that the data is there but wont let me exstract the value?
Upvotes: 1
Views: 1781
Reputation: 81
When trying to access the Snapshot properties use childSnapshot(forPath:)
see another example here.
But basically would look like:
for child in snapshot.children.allObjects as! [FIRDataSnapshot] {
let firstname = child.childSnapshot(forPath: "first_name").value as? String
}
Upvotes: 2
Reputation: 489
Your snapshot contains the value "12345UIDEXample" on the first level of children.
To access the data you are looking for you can use a loop through the children casting as a FIRDataSnapshot.
for child in snapshot.children.allObjects as! [FIRDataSnapshot]{
let firstname = child.value!["first_name"] as? String
}
In this example child value will only return another snapshot of your object like so:
Snap(12345UIDEXample) {
"first_name" = Bob;
"last_name" = Someone;
"profile_picture_url" = "exampleurl.com";
username = bobby;
};
However you will be able to access the desired fields as you tried to previously.
Upvotes: 6