1
我現在有一個觀察手柄,用於檢查何時添加新通道。我希望它是一個帶有按鈕的observeSingleEvent,當用戶點擊它時將重新加載頻道。 observeSingleEvent正常工作。這是代碼:轉換觀察到在Firebase中觀察SingleSvent時出錯
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()是表示沒有錯誤。謝謝。
謝謝。我需要添加channelSnap! FIRDataSnapshot使其工作。 – Petravd1994
啊,是的......我從來不確定那些在Swift中的咒語。很高興聽到這是足夠的。你能編輯我的答案來添加代碼片段嗎?否則,我會把它放在錯誤的地方。 –
做到了!再次感謝你 :)。 – Petravd1994