我在一个函数中尝试从Firebase检索两组数据时遇到问题。在检索之后,此检索的结果将用于更新进度条(否则为“零”值),因此此进度条'功能也包含在Firebase功能中。为了进一步说明,我正在努力获取“用户帖子”和“用户计划”的条目数量。来自Firebase Db: -
该函数的代码如下所示(然后我会告诉您这是什么问题!): -
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
}
})
}
})
问题:用户计划的当前计数'是18.用户帖子的当前数量'那么分数应该等于0.77(78%)。但是,'用户帖子'似乎重复18次,所以计数是252(即14 * 18)!!在过去的3天里,我尝试过各种修复方法,但结果总是一样。 任何想法都很受欢迎,并会阻止我向妻子发誓......
答案 0 :(得分:1)
您可以使用snapshot.childrenCount
来获取快照子项的计数,并且需要将计算移动到循环外的分数
结帐此代码
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)")
})
});
}