0

I have a chat feature in an iOS app. the chat previews are presented in a tableView and I am using a class for the TableView cells themselves. I want to listen for new messages so I can put a "new Message" label on the cells. The relevant parts of the tableView Cell are:

    var chat: Chat! {
    didSet {
        self.updateUI()
        self.observeNewMessages()
    }
    }

    extension ChatTableViewCell {

        func observeNewMessages() {

        let chatMessageIdsRef = chat.ref.child("messageIds")  
        chatMessageIdsRef.observe(.childAdded, with: { snapshot in

        let messageId = snapshot.value as! String
        DatabaseReference.messages.reference().child(messageId).observe(.childAdded, with: { snapshot in
            //let message = Message(dictionary: snapshot.value as! [String : Any])


            print("looks like there is a new message") //works
            self.messageLabel.text = "New Message!"
            //self.delegate?.newMessage()
        })
        })
        }
    }

The print statement is there to test the listener. The problem I am having is when the table view loads and the cells get created, observeNewMessages() is executing the print statement regardless of whether there were new messages. It is just reading the old children that are already there first? Obviously this is going to cause the message label to always read "New Message." I'm not too good with Firebase so is there a better Firebase function to use or a better way to do this?

*I am using 2 queries because the Message dictionary will allow me to see if the current user made the message or not. The delegate is there because my next step will be to reload the tableview -- as it is now, this will also cause an infinite print statement loop...

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Sente
  • 277
  • 4
  • 11
  • .childAdded returns all of the children under the node you're listening to the first time it fires. Then it returns just the information for the newly added child. I think you can use a boolean flag distinguish the initial load from subsequent events. – DoesData Aug 29 '17 at 20:24
  • It is possible to detect initial data vs new data. See [this answer](https://stackoverflow.com/a/27995609/4816918) – Jeff Aug 29 '17 at 20:45
  • each chat has a unique ID that I could use as a key for UserDefaults and set a Boolean. if it is true (initially shown) then I could not re-execute observeNewMessages. would the original listeners still be active? – Sente Aug 29 '17 at 20:49

0 Answers0