When I query a specific child I get all the results back instead of the ones specific to what I'm looking for:
For eg if my search text begins with the letter "c" I should only get the cat and the cow from below but for some reason I'm also getting the bull.
root
|
@---users
|
@---uid_1000
| |--uid: "uid_1000"
| |--username: "bull"
|
@---uid_2000
| |--uid: "uid_2000"
| |--username: "cat"
|
@---uid_3000
|--uid: "uid_3000"
|--username: "cow"
I was thinking maybe the issue is because I seem to grab everything at the users node (dictionaries plural) and then loop through the dictionaries that might be the issue but then I realized it should still only be the username values beginning with the letter "c" that should appear inside the dictionaries to begin with and bull should get skipped.
Where am I going wrong at?
let searchText = "c"
let ref = Database.database().reference().child("users")
.queryOrdered(byChild: "username")
.queryStarting(atValue: searchText)
.queryEnding(atValue: searchText + "\u{f8ff}")
ref?.observeSingleEvent(of: .value, with: { (snapshot) in
if !snapshot.exists() { return }
// dictionaries plural
guard let dictionaries = snapshot.value as? [String: Any] else { return }
dictionaries.forEach({ (key, value) in
guard let dict = value as? [String: Any] else { return }
let user = User(dict: dict)
let isContained = self.users.contains(where: { (containedUser) -> Bool in
return user.uid == containedUser.uid
})
if !isContained {
self.users.append(user)
self.collectionView.reloadData()
}
})
Updated with Json per Frank's request:
{
"users" : {
"1000" : {
"userId" : "1000",
"username" : "bull"
},
"2000" : {
"userId" : "2000",
"username" : "cat"
},
"3000" : {
"userId" : "3000",
"username" : "cow"
}
}
}
A picture to match. I excluded the other 2 objects from the json because even though they showed up on my end (I actually got 5 results) I wanted to just focus on what's in the question which is the first 3.