首页 文章

Swift Firebase - 尝试在函数中检索多组数据以计算条目数

提问于
浏览
1

我在一个函数中尝试从Firebase检索两组数据时遇到问题 . 在检索之后,此检索的结果将用于更新进度条(否则为'zero'值),因此此'progress bar'函数也包含在Firebase函数中 . 为了进一步澄清,我试图从Firebase Db获取'user-posts'和'user-plans'的条目数: -
enter image description here

enter image description here

函数的代码看起来像这样(然后我会让你知道问题是什么!): -

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.当前的“用户帖子”数为14.因此该分数应该等于0.77(78%) . 但是,“用户帖子”的数量似乎重复了18次,所以计数是252(即14 * 18)!!在过去的3天里,我尝试了各种修复方法,但结果总是相同的 . 任何想法都很受欢迎,并会阻止我发誓妻子......

1 回答

  • 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)")
    
            })
    
        });
    
    }
    

相关问题