juelizabeth juelizabeth -4 years ago 157
Swift Question

Add value to Firebase database

I am trying to get the timestamp feature to work on my app but it is not. I am building a chat app with

. For every message a user sends, I want it to be displayed in my database.

So far this is the code I have:


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) {

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

Here is a screenshot of my database:
enter image description here

Answer Source

Change this line:

let messageData = snapshot.value as! [String: AnyObject]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download