如何检查 Firebase 分支是否存在于多个级别

问题描述 投票:0回答:1

我正在努力寻找解决当前问题的方法。

我有一位用户需要查看他们是否已完成所有勾选框。非常感谢任何解决方案。

我有一个读取快照的参考。根据快照,我从该快照中获得了这些密钥,然后我可以使用它们来获取另一组密钥,我用这些密钥来查看用户是否已获得该密钥。 (希望这是有道理的)。

我能够获取第一部分,但越深入,我的 For/In 循环就会不断重复,因此当我只想要用户将其标记为绿色的文本(KPI 或目标)时,所有文本都会标记为绿色而他/她没有达到的则被涂成黑色。

请参阅下面的代码。

func checkStudentKpiAchievements(){
    
    StudentUID = UserDefaults.standard.string(forKey: "StudentUID") ?? "Nil"

    let myRef = Database.database().reference().child("KpisInThatLevel").child("Starfish")
    
        myRef.observeSingleEvent(of: .value, with: { snapshot1 in
            
            let childSnaps = snapshot1.children.allObjects as! [DataSnapshot]
                                
                for child in childSnaps {
                    
                    Database.database().reference().child("AttainedKpisFromStudents").child("Starfish").child(child.key).observe(.value, with: { snapshot2 in
                      
                        let yesAchieved = snapshot2.childSnapshot(forPath: self.StudentUID)
           
                        if (yesAchieved.hasChildren()) {
                            
                            print(true)
                            self.kpiDescription.textColor = UIColor.green

                            
                        } else {
                            
                            self.kpiDescription.textColor = UIColor.black

                        }
                     
                    })
                }
              
        })

}
swift firebase firebase-realtime-database
1个回答
0
投票

据我所知,我不确定代码流的确切意图是您想要传递从一个

snapshot1
检索到的密钥,以将它们作为
snapshot2
传递到下一个查询。

所以请尝试以下方法,如果这对您有用的话

func checkStudentKpiAchievements() {
    StudentUID = UserDefaults.standard.string(forKey: "StudentUID") ?? "Nil"
    
    let myRef = Database.database().reference().child("KpisInThatLevel").child("Starfish")
    
    myRef.observeSingleEvent(of: .value, with: { snapshot1 in
        let childSnaps = snapshot1.children.allObjects as! [DataSnapshot]
        
        for child in childSnaps {
            Database.database().reference().child("AttainedKpisFromStudents").child("Starfish").child(child.key).observe(.value, with: { snapshot2 in
                let yesAchieved = snapshot2.childSnapshot(forPath: self.StudentUID)
                
                if (yesAchieved.hasChildren()) {
                    print(true)
                } else {
                    print(false)
                }
            })
        }
        
       
        self.kpiDescription.textColor = UIColor.green 
      //take this out of for loop
    })
}

虽然假设这只是执行所有这些读取的目的之一,但我确信可能有更好、更有效的方法来执行此操作,但为此您需要重组数据库。 如果您有其他函数使用并证明在当前结构中更有效,那么就坚持使用它。

© www.soinside.com 2019 - 2024. All rights reserved.