Reputation:
I'm trying to get the count of everyone how has tapped going by returning all the users whose values equal to 1. Is this the proper way of doing it. Below is the function I'm using to set if they are going. Can someone help me return the count of everyone going
func didTapGoing(for cell: HomePostCell) {
guard let indexPath = collectionView?.indexPath(for: cell) else { return }
var post = self.posts[indexPath.item]
guard let postId = post.id else { return }
guard let uid = FIRAuth.auth()?.currentUser?.uid else { return }
let values = [uid: post.isGoing == true ? 0 : 1]
FIRDatabase.database().reference().child("going").child(postId).updateChildValues(values) { (err, _) in
if let err = err {
print("Failed to pick going", err)
return
}
post.isGoing = !post.isGoing
self.posts[indexPath.item] = post
self.collectionView?.reloadItems(at: [indexPath])
}
}
Upvotes: 1
Views: 1921
Reputation: 598797
The code you shared doesn't read any data, but only updates it with updateChildValues
.
To count the number of child nodes, you'll need to read those nodes and then call DataSnapshot.childrenCount
.
FIRDatabase.database().reference().child("going").child(postId).observe(DataEventType.value, with: { (snapshot) in
print(snapshot.childrenCount)
})
If you only want to count the child nodes that have a value of 1, you'd do:
FIRDatabase.database().reference().child("going").child(postId)
.queryOrderedByValue().queryEqual(toValue: 1)
.observe(DataEventType.value, with: { (snapshot) in
print(snapshot.childrenCount)
})
For more on this, read the Firebase documentation on sorting and filtering data.
Upvotes: 7