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

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

问题描述

我有一个字符串数组,我正在尝试通过 firebase 填充它.它是一个聊天应用程序,当用户创建房间时,他或她会为房间命名.当用户登录并进入登录页面时,它会查询他或她参与的所有房间,我希望它填充 tableview.在 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
}

我收到一个错误,说 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.

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

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