使用 Swift 3 计算 children 的 Firebase

Firebase with Swift 3 counting the number of children

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

    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 是一个 get only 属性。 我如何填充该数组计数?

我猜 "rooms" 是 class 个房间的数组。

"an error that count is a get only property" 当您尝试设置数组的范围时会发生 "rooms" - 您不能那样做。

'count' 属性是只读访问。 在人的语言中,它就像。你有一个包。你在袋子里放了一个苹果。你又往袋子里放了一个苹果。现在你有 2 个苹果。你不能只说 "My bag have 2 apples."

修复它:

  • 您必须为每个快照创建类型为 'Room' class 的变量:FIRDataSnapshot
  • 将其添加到房间。

示例:

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)

    let room = Room()
    // Use you snapshot(FIRDataSnapshot) to create the data of the room.
    rooms.append(room)
})

return rooms.count

}

Firebase 数据是异步加载(和同步)的。如果您添加一些调试日志记录,这是最容易看到的:

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

当您 运行 这段代码时,日志输出将是:

Start observing

Returning count

Got snapshot

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

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

我的方法是关闭。呼叫完成后,它将 return children

的号码
typealias countAllPostsResult = (UInt) -> Void
class func countAllPosts(isDeleted: Bool,completedHandler: @escaping countAllPostsResult) {
    print("countAllPosts ...is running...", isDeleted)
    var dataSnapshot = [DataSnapshot]()

    Constants.Commons.posts_node_ref.queryOrdered(byChild: Constants.Posts.is_deleted).queryStarting(atValue: "false").queryEnding(atValue: "false\u{f8ff}").observeSingleEvent(of: .value, with: { (snapshot) -> Void in

        for snap in snapshot.children {
            dataSnapshot.append(snap as! DataSnapshot)
        }
        if dataSnapshot.count > 0 {
            completedHandler(UInt(dataSnapshot.count))
        } else {
            completedHandler(0)
        }
    })

}