0

I would like to display the chats in chronological order. I am using Firebase and JSQMessageViewController. I would think that the problem is somewhere in the observeConversations function. However I have not figured out the correct way to display the chats in chronological order. They are currently being displayed completely randomly.

 override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    observeConversations()
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return conversations.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "chatCell", for: indexPath) as! ChatTableViewCell
    cell.setConversation(conversations[indexPath.row])
    return cell
}

func observeConversations() {
    guard let user = Auth.auth().currentUser else { return }
    let ref = Database.database().reference().child("conversations/users/\(user.uid)")
    ref.observe(.value, with: { snapshot in

        var _conversations = [Conversation]()
        for child in snapshot.children {

            if let childSnap = child as? DataSnapshot,
                let dict = childSnap.value as? [String:Any],
                let key = dict["key"] as? String,
                let sender = dict["sender"] as? String,
                let recipient = dict["recipient"] as? String,
                let text = dict["text"] as? String,
                let timestamp = dict["timestamp"] as? Double,
                let muted = dict["muted"] as? Bool, !muted,
                let seen = dict["seen"] as? Bool {

                let date = Date(timeIntervalSince1970: timestamp/1000)
                let conversation = Conversation(key: key, sender: sender, recipient: recipient, date: date, recentMessage: text, seen: seen)
                _conversations.append(conversation)
            }
        }
        self.conversations = _conversations
        self.tableView.reloadData()

    })
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
ggtechllc
  • 45
  • 1
  • 6

1 Answers1

0

If you want to retrieve the items ordered by timestamp:

let ref = Database.database().reference().child("conversations/users/\(user.uid)")
ref.orderQuery(byChild: "timestamp").observe(.value, with: { snapshot in
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • it orders the new ones from bottom to top, is there a way I can order them top to bottom? Being the newest ones on top instead of bottom? – ggtechllc Feb 12 '18 at 19:40
  • There is no operator to order queries descending in Firebase. See https://stackoverflow.com/questions/34156996/firebase-data-desc-sorting-in-android – Frank van Puffelen Feb 12 '18 at 19:50