我正在尝试使用Swift和Firebase编写一个消息传递应用程序,它似乎可以在75%的时间内平稳运行,但每次都会崩溃,因为多条消息都是作为快照而不是一个快照引入的。
我在我的代码中添加了print语句来打印有问题的快照,这里是代码和控制台输出:
以下是代码:
private func observeMessages() {
let messagesQuery = messageReference!.queryLimitedToLast(25)
messagesQuery.observeEventType(.ChildAdded, withBlock: {snapshot in
print(snapshot.value)
print(snapshot.value!["senderId"])
let id = snapshot.value?["senderId"] as! String
let text = snapshot.value?["text"] as! String
self.addMessage(id, text: text)
self.finishReceivingMessage()
})
}
控制台顺利运行时的输出:
Optional({
senderId = mVHbzSGdSIS4mIkeprRWZtKtdow2;
text = Did;
}) //Print statement for snapshot.value!
Optional(mVHbzSGdSIS4mIkeprRWZtKtdow2)
//Print statement for snapshot.value!["senderId"]
错误时控制台的输出:
Optional({
"-KLSJznUSC_alQSoTP9G" = {
senderId = mVHbzSGdSIS4mIkeprRWZtKtdow2;
text = Test;
};
"-KLSK1fTfCBXsCp9Flul" = {
senderId = mVHbzSGdSIS4mIkeprRWZtKtdow2;
text = Test;
};
}) //Print statement for snapshot.value!
nil //Print statement for snapshot.value!["senderId"]
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
正如您所看到的,当代码失败时,快照似乎会引入两个不同的消息,而不是一个消息,我不太确定为什么会这样。
更新 - 请参阅下面有关向Firebase添加数据的代码块:
override func didPressSendButton(button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: NSDate!) {
let itemRef = messageReference!.childByAutoId()
let messageItem = [
"text": text,
"senderId": senderId
]
itemRef.setValue(messageItem)
JSQSystemSoundPlayer.jsq_playMessageSentSound()
finishSendingMessage()
}