Reputation: 37
I have a problem trying to retrieve two sets of data from Firebase, in one function. The results from this retrieve will be used to update a progress bar, after the retrieve (otherwise 'zero' values) so this 'progress bar' function is also included in the Firebase function. To clarify further, I am trying to get the count of entries for 'user-posts', and 'user-plans' from the Firebase Db:-
The code for the function looks like this (and then I'll let you know what the issue is!):-
func firebaseRetrieve() {
guard let uid = Auth.auth().currentUser?.uid else {return}
let planRef = DB_BASE.child("user-plan").child(uid)
planRef.observeSingleEvent(of: .value, with: { (snapshot) in
for child in snapshot.children {
let snap = child as! DataSnapshot
let key = snap.key
self.totalPlans.append(key)
self.planCount = Double(self.totalPlans.count)
let postRef = DB_BASE.child("user-posts").child(uid)
postRef.observeSingleEvent(of: .value, with: { (snapshot) in
for child in snapshot.children {
let snaps = child as! DataSnapshot
let keys = snaps.key
self.totalPosts.append(keys)
self.postCount = Double(self.totalPosts.count)
self.fraction = self.postCount / self.planCount
//THIS IS WHERE I INPUT ANOTHER FUNCTION TO PASS THE VALUE OF 'FRACTION' INTO, THAT THNE DETERMINES THE PROGRESS BAR
}
})
}
})
THE ISSUE: The current count of 'user-plan' is 18. The current count of 'user-posts' is 14. So the fraction should equal 0.77 (78%). But, the count of 'user-posts' seems to be reiterated 18 times, so the count is 252 (i.e. 14 * 18)!! I've tried all sorts to fix it over the past 3 days, but always the same result. Any ideas greatly received, and will stop me swearing at the wife......
Upvotes: 1
Views: 70
Reputation: 18592
you can use snapshot.childrenCount
to get the count of the snapshot children , and you need to move your calculation for fraction outside the loop
checkout this code
func firebaseRetrieve()
{
guard let uid = Auth.auth().currentUser?.uid else {return}
let planRef = DB_BASE.child("user-plan").child(uid)
planRef.observeSingleEvent(of: .value, with:
{
(snapshot) in
self.planCount = snapshot.childrenCount;
for child in snapshot.children
{
let snap = child as! DataSnapshot
let key = snap.key
self.totalPlans.append(key)
}
let postRef = DB_BASE.child("user-posts").child(uid)
postRef.observeSingleEvent(of: .value, with:
{
(snapshot) in
self.postCount = snapshot.childrenCount;
for child in snapshot.children
{
let snaps = child as! DataSnapshot
let keys = snaps.key
self.totalPosts.append(keys)
}
self.fraction = self.postCount / self.planCount;
print("fraction = \(self.fraction)")
})
});
}
Upvotes: 1