我现在有一个观察手柄,可以在添加新频道时进行检查。我希望它是一个带有按钮的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()没有显示错误。谢谢您。
最佳答案
你不仅从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)
关于swift - 在Firebase中将观察转换为observeSingleEvent时出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42508816/