I\'m creating a simple chat app to learn Swift and Firebase. I have a query that checks for a chat room\'s messages to load into a tableView. The query returns a snapshot bu
As Pipiks explained, your issue is that you are attempting to access individual message details at one level higher than the returned data.
The snapshot value is giving you a dictionary of chat messages, where the top level's keys are the chat message keys. To map your returned data to an array of messages, I would use the following code:
query.observeSingleEvent(of: .childAdded, with: { snapshot in
guard let messagesDict = snapshot.value as? [String: AnyObject] else { return }
self.messages = messagesDict.flatMap({ (messageId: String, messageData: Any) -> Message? in
guard
let sender = messageData["sender"] as? String,
let text = messageData["text"] as? String,
let timestamp = messageData["timestamp"] as? Int,
let message = Message(key: messageKey, sender: sender, text: text, timestamp: timestamp) else {
return nil
}
return message
})
self.tableView.reloadData()
})
What this does is map your dictionary of messages to an array of Message objects.
I have used a flatMap to filter out any messages which do not have sender, text or timestamp values (so the flatMap returns a [Message] object).
Does that solve the issue?