我正在尝试使用时间戳功能来处理我的应用,但事实并非如此。我正在使用JSQMessagesViewController
构建聊天应用。对于用户发送的每条消息,我希望它显示在我的数据库中。
到目前为止,这是我的代码:
//ADD A NEW MESSAGE
let timeStamp = NSNumber(value: Int(NSDate().timeIntervalSince1970))
private func addMessage(withId id: String, name: String, text: String, time: NSNumber) {
if let message = JSQMessage(senderId: id, displayName: name, text: text) {
messages.append(message)
}
}
override func didPressSend(_ button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: Date!) {
let itemRef = rootRef.child("messages").child("\(self.convoId!)").childByAutoId() // 1
let messageItem = [ // 2
"senderId": senderId!,
"ReceiverId": senderDisplayName!,
"text": text!,
"timestamp": timeStamp,
] as [String : Any]
itemRef.setValue(messageItem) // 3
JSQSystemSoundPlayer.jsq_playMessageSentSound() // 4
finishSendingMessage() // 5
isTyping = false
}
private func observeMessages() {
// 1.
let messageQuery = rootRef.child("messages/\(self.convoId!)").queryLimited(toLast: 25)
// 2. We can use the observe method to listen for new
// messages being written to the Firebase DB
newMessageRefHandle = messageQuery.observe(.childAdded, with: { (snapshot) -> Void in
// 3.
let messageData = snapshot.value as! Dictionary<String, String>
if let id = messageData["senderId"] as String!, let name = messageData["ReceiverId"] as String!, let text = messageData["text"] as String!, let time = messageData["timeStamp"] as Any!, text.characters.count > 0 {
// 4.
self.addMessage(withId: id, name: name, text: text, time: time as! NSNumber)
// 5
self.finishReceivingMessage()
}
答案 0 :(得分:1)
更改此行:
let messageData = snapshot.value as! [String: AnyObject]
答案 1 :(得分:0)
直接发送时间戳,无需将其转换为nsnumber
override func didPressSend(_ button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: Date!) {
let itemRef = rootRef.child("messages").child("\(self.convoId!)").childByAutoId() // 1
let messageItem = [ // 2
"senderId": senderId!,
"ReceiverId": senderDisplayName!,
"text": text!,
"timestamp": NSDate().timeIntervalSince1970,
] as [String : Any]
itemRef.setValue(messageItem) // 3
JSQSystemSoundPlayer.jsq_playMessageSentSound() // 4
finishSendingMessage() // 5
isTyping = false
}