带有Swift 3的Firebase计算孩子的数量 [英] Firebase with Swift 3 counting the number of children

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

问题描述

我有一个字符串数组,我正在尝试通过Firebase填充它.它是一个聊天应用程序,当用户创建房间时,他或她将房间命名.当用户登录并进入登录页面时,它将查询他或她正在参与的所有房间,我希望该房间能够填充表格视图.在firebase文档中,我找到了childrenCount,但似乎无法正常工作.这是我到目前为止尝试过的

I have an array of strings and I am trying to populate it through firebase. It is a chat application and when a user creates a room he or she names the room. When the user logs in and goes to the landing page it queries all the rooms that he or she is participating in and I want that to fill the tableview. In the firebase docs i found childrenCount but I cannot seem to get it to work. This is what I have tried so far

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    let ref = firebase.child("users").child(fUID).child("participating")

    ref.observe(.value, with: { (snapshot: FIRDataSnapshot!) in
        print(snapshot.childrenCount)
        rooms.count = snapshot.childrenCount
    })

    return rooms.count
}

我得到一个错误,计数是一个只能获得的属性. 我如何填充该数组计数?

I get an error that count is a get only property. How to i populate that array count?

推荐答案

Firebase数据是异步加载(和同步)的.这很容易查看是否添加了一些调试日志记录:

Firebase data is loaded (and synchronized) asynchronously. This is easiest to see if you add some debug logging:

let ref = firebase.child("users").child(fUID).child("participating")

print("Starting observing");
ref.observe(.value, with: { (snapshot: FIRDataSnapshot!) in
    print("Got snapshot");
    print(snapshot.childrenCount)
    rooms.count = snapshot.childrenCount
})

print("Returning count");
return rooms.count

运行此代码段时,日志记录输出将为:

When you run this snippet, the logging output will be:

开始观察

退货计数

获得快照

这可能不是您期望的输出顺序.这也解释了您的计数永远不会正确的原因:数据尚未加载,因此无法计数.

This is probably not the order you expected the output to be in. And it also explains why your count will never be correct: the data hasn't been loaded yet, so it can't be counted.

这是Firebase侦听器使用回调块的原因:当数据同步时,将调用该块.

This is the reason why Firebase listeners work with callback blocks: the block is invoked when the data is synchronized.

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

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