很难弄清楚如何遍历我的消息数据库,这样我就可以找到一个与用户电话号码相匹配的密钥......这种方法崩溃了以及我试过的所有其他方法也失败了。我真的可以使用帮助谢谢。
func retrieveMessages(){
let messagesDB = Database.database().reference().child("iMessenger/Messages")
messagesDB.observe(.childAdded, with: {(snapshot) in
let snapshotValue = snapshot.value as! Dictionary<String, String>
//This conditional is suppose to filter out messages that aren't to or from the user
if snapshotValue["sender"]! == userPhoneNumber || snapshotValue["receiver"]! == userPhoneNumber{
let text = snapshotValue["messageBody"]!
let sender = snapshotValue["sender"]!
let message = Message()
message.messageBody = text
message.sender = sender
self.messageArr.append(message)
self.configureTableView()
self.messagesTableView.reloadData()
self.scrollToLastRow()}}
)}
答案 0 :(得分:0)
您不应该尽可能在代码中使用!
,如果值为nil
,则必然会崩溃,我认为您需要将值向下转换为String
比较电话号码,因此您可以按如下方式修改您的代码:(使用可选的绑定和向下转换)
if let snapshotValue = snapshot.value as? [String: Any], let senderNumber = snapshotValue["sender"] as? String,let receiverNumber = snapshotValue["receiver"] as? String {
//now you should compare these values as follows...
if senderNumber == userPhoneNumber || receiverNumber == userPhoneNumber {
//do your stuff...
}
}