0

I have a chat screen that uses Firebase. I am using the following code:

    ref2.observeEventType(.ChildAdded, withBlock: { snapshot in
        let msg = snapshot.value.objectForKey("message")!
        self.addMsg(String(msg))
    })

func addMsg(m:String) {
    txtChat.text = txtChat.text + "\r\n" + m
}

It works properly but when you first connect to the database, it processes all of the previous messages. I would like to fix it so a user will only see the messages that were added while he was in the room.

JeffG
  • 13
  • 3
  • What determines 'while he was in the room'? – Jay Apr 22 '16 at 19:55
  • New messages sent after connecting to the database. The above code pulls in all the historic messages. For example, Chris and Jeff are chatting. Now, John loads the app and connects to the database. I would like him just to see anything typed after this point. But as soon as the program loads, all the prior messages are added to the textbox. – JeffG Apr 22 '16 at 20:10
  • See http://stackoverflow.com/questions/18270995/how-to-retreive-only-new-data for the most common approach. But a way better approach would be to keep track of when the user last was connected and then query for new message with `ref.queryOrderedByChild("timestamp").queryStartingAtValue(lastSeenTimestamp)` – Frank van Puffelen Apr 22 '16 at 20:36

1 Answers1

0

I decided to just clear the database when a new client connects before they read from it. That way they will not get any old messages and only get anything typed after they connect.

let profile = ref3.ref.childByAppendingPath("mainChat")
profile.removeValue()
ref2.observeEventType(.ChildAdded, withBlock: { snapshot in
let msg = snapshot.value.objectForKey("message")!
    self.addMsg(String(msg))
})

func addMsg(m:String) {
    txtChat.text = txtChat.text + "\r\n" + m
}
JeffG
  • 13
  • 3