如何计算所有UID(不只是currentUser)下的子代?

时间:2019-05-16 17:54:38

标签: swift firebase firebase-realtime-database

我正在使用Xcode 10,Swift 5和firebase实时数据库。我想计算所有用户添加到数据库中的项目总数。

override func viewDidLoad() {
    super.viewDidLoad()
    //get reference to firebase database
    refRepairs = Database.database().reference().child("completed");


    //observing the data changes
    refRepairs!.child(UserID!).observe(DataEventType.value, with: { (snapshot) in

        //if the reference have some values
        let num = snapshot.childrenCount
        //print(num)

        self.numberOfCompletedItems.text = String (num)
    })

    refRepairs!.child(UserID ?? "No User ID").observe(.childAdded, with: { (snapshot) in
        //// Attempt to fetch the number of projects
        let num = snapshot.childrenCount
        print("SnapShot Child Number: \(num)")

    })
}

运行代码时,它显示0。我需要弄清楚如何计算所有用户ID下的子代数。谢谢。

Firebase Database Picture

1 个答案:

答案 0 :(得分:0)

也许您需要使用.childAdded来遍历该集合中的每个节点。

更新

1-此代码将提取root目录中的用户:

func fetchRoot() {
    refRepairs!.child(UserID ?? "No User ID").observe(.childAdded, with: { (snapshot) in
            // Get Every user 
            let userID = snapshot.key
            // Pass the users key
            self.fetchUsers(userID: userID)

        })
    }
}

2-此代码将计算users内的每个节点:

func fetchUsers(userID: String) {
    refRepairs!.child(userID).observeSingleEvent(of: .value, with: { (snapshot) in
            //// Attempt to fetch the number of projects
            let num = snapshot.childrenCount
            print("SnapShot Child Number: \(num) -- For User: \(userID)")
        })
    }
}