简体   繁体   中英

Query to count number followers swift 4

I'm trying to count the number of followers the user has from my firebase database but no success. The number of followers is returning any value. When a user follows another user it creates a node in firebase with the userID and a Int value of 1 as shown below.

 fileprivate func countTrusting() {

    guard let userId = self.user?.uid else { return }

    guard let currentLoggedInUser = Auth.auth().currentUser?.uid else { return }

    Database.database().reference().child("following").child(userId).queryOrderedByValue().queryEqual(toValue: 1).observe(DataEventType.value, with: { (snapshot) in

        let count = String(snapshot.childrenCount)
        self.trustedLabel.text = "\(count) \nFollowing"

    }) { (error) in
        print("There was an error getting the following count:", error)
    }
}

My firebase database

在此处输入图片说明

If I understand the question, you want to have a count of the number of followers of a user. In that case, there's no need for a query as the only nodes that will exist are the users followers.

This code reads in the child followers nodes and prints the count.

let userFollowingRef = fbRootRef.child("following").child("some_user_uid")
userFollowingRef.observeSingleEvent(of: .value, with:  { snapshot in
    print(snapshot.childrenCount)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM