Swift 4和Firebase如何计算子值 [英] Swift 4 and Firebase How to count child values

查看:61
本文介绍了Swift 4和Firebase如何计算子值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过返回值等于1的所有用户来获取开发者的计数.这是正确的方法吗?下面是我要设置的功能.有人可以帮我归还所有人的人数

I'm trying to get the count of everyone how has tapped going by returning all the users whose values equal to 1. Is this the proper way of doing it. Below is the function I'm using to set if they are going. Can someone help me return the count of everyone going

func didTapGoing(for cell: HomePostCell) {
    guard let indexPath = collectionView?.indexPath(for: cell) else { return }
    var post = self.posts[indexPath.item]

    guard let postId = post.id else { return }

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

    let values = [uid: post.isGoing == true ? 0 : 1]
    FIRDatabase.database().reference().child("going").child(postId).updateChildValues(values) { (err, _) in

        if let err = err {
            print("Failed to pick going", err)
            return
        }

        post.isGoing = !post.isGoing
        self.posts[indexPath.item] = post
        self.collectionView?.reloadItems(at: [indexPath])
    }
}

推荐答案

您共享的代码不会读取任何数据,而只会使用updateChildValues更新它.

The code you shared doesn't read any data, but only updates it with updateChildValues.

要计算子节点的数量,您需要读取这些节点,然后调用

To count the number of child nodes, you'll need to read those nodes and then call DataSnapshot.childrenCount.

FIRDatabase.database().reference().child("going").child(postId).observe(DataEventType.value, with: { (snapshot) in
  print(snapshot.childrenCount)
})

如果只想计算值为1的子节点,则可以这样做:

If you only want to count the child nodes that have a value of 1, you'd do:

FIRDatabase.database().reference().child("going").child(postId)
  .queryOrderedByValue().queryEqual(toValue: 1)
  .observe(DataEventType.value, with: { (snapshot) in
    print(snapshot.childrenCount)
  })

有关更多信息,请阅读排序上的Firebase文档和过滤数据.

For more on this, read the Firebase documentation on sorting and filtering data.

这篇关于Swift 4和Firebase如何计算子值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆