我现在有一个观察句柄,可以检查添加新频道的时间。我希望它是一个带有按钮的observeSingleEvent,当用户点击它时会重新加载频道。 observeSingleEvent正常工作。这是代码:
private func observeChannels() {
channelRefHandle = channelRef.observe(.childAdded, with: { (snapshot) -> Void in
self.playersInChannnel.append("\(snapshot.childrenCount)")
let channelData = snapshot.value as! Dictionary<String, AnyObject>
let id = snapshot.key
if let name = channelData["name"] as! String!, name.characters.count > 0 {
self.channels.append(Channel(id: id, name: name))
self.tableView.reloadData()
} else {
print("Error! Could not decode channel data")
}
})
}
我现在尝试将它转换为observeSingleEvent,把打印说错误,无法解码通道数据。这是我的代码:
func reloadChannels()
{
channelRef.observeSingleEvent(of: .value, with: { (snapshot) -> Void in
self.playersInChannnel.append("\(snapshot.childrenCount)")
let channelData = snapshot.value as! Dictionary<String, AnyObject>
let id = snapshot.key
if let name = channelData["name"] as! String!, name.characters.count > 0 {
self.channels.append(Channel(id: id, name: name))
self.tableView.reloadData()
} else {
print("Error! Could not decode channel data")
}
})
}
这段代码有什么问题?这是来自observeSingleEvent的快照的打印:
Snap (channels) {
"-Ke3g8tLH9A-_iTVjQhq" = {
"-Ke3g8tO2XPCbyIjP4Op" = {
PictureVersion = "";
userID = keVlTMUXyRViUsTVjTnKdvZs7mg1;
username = pietje;
};
name = test;
};
"-Ke3gFbijlcQGuJXe42L" = {
"-Ke3gFbjsEgpA3wjM1Jv" = {
PictureVersion = "";
userID = keVlTMUXyRViUsTVjTnKdvZs7mg1;
username = pietje;
};
name = test2;
};
}
Error! Could not decode channel data
同样,触发observeChannels()显示没有错误。谢谢。
答案 0 :(得分:2)
您没有从observe
更改为observeSingleEvent
,您也从观察.childAdded
切换到观察.value
。由于您现在正在侦听.value
,这意味着您获得的快照一次包含所有子节点(即使只有一个匹配的子节点) )。
因此,您需要遍历快照的子项,以获取之前的频道数据:
func reloadChannels()
{
channelRef.observeSingleEvent(of: .value, with: { (snapshot) -> Void in
self.playersInChannnel.append("\(snapshot.childrenCount)")
for channelSnap in snapshot.children {
let channelData = (channelSnap as! FIRDataSnapshot).value as! Dictionary<String, AnyObject>
let id = (channelSnap as! FIRDataSnapshot).key
if let name = channelData["name"] as! String!, name.characters.count > 0 {
self.channels.append(Channel(id: id, name: name))
self.tableView.reloadData()
} else {
print("Error! Could not decode channel data")
}
}
})
}
有关如何循环快照子项的更多信息,请参阅此问题的答案:Iterate over snapshot children in Swift (Firebase)