0

I am doing a chat messenger app, and i would like to show the last sent message on home menu as shown:

enter image description here

and my database looks like

enter image description here

in my view did load, i am putting a function of getAllMsg()

    override func viewDidLoad() {
    super.viewDidLoad()
    self.title = "Private Message"
    // Do any additional setup after loading the view.
    getAllMsg()
}

But in my getAllMsg() function, I am unsure how should I access the last message for each recipient. I used this code:

func getAllMsg() {
    self.users = []

    let ref = Database.database().reference().child("privateMessages")
    ref.queryLimited(toLast: 1).observeSingleEvent(of: .childAdded) { (snapshot) in
        print(snapshot)
    }
        }

and I am getting the whole messages sent to my last recipient. Does anyone have any idea how should I go about this?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
William Loke
  • 377
  • 1
  • 4
  • 25

1 Answers1

0

You're calling Database.database().reference("privateMessages").queryLimited(toLast: 1), which means that the database goes to /privateMessages and then gets the last child under that. That child is an entire user's worth of messages, not just the last message.

If you want the last message for a specific user you should start your query at that user's node:

// this code assumes there is a current user
let user = Auth.auth().currentUser
let ref = Database.database().reference("privateMessages").child(user.uid)

Now you want to query this user's messages, assumedly either by timestamp or by the key (which is also chronological). For the latter you'd do:

ref.queryOrderedByKey().queryLimited(toLast: 1).observeSingleEvent(of: .childAdded) { (snapshot) in
    print(snapshot)
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • but there isn't any user.uid nodes, the nodes were named after senderID_receiverID... – William Loke May 04 '18 at 02:43
  • Ah... then you'll need to know the UIDs of both users. Firebase Database filters and returns the child nodes directly under the location where you execute the query. It cannot skip a level. See https://stackoverflow.com/questions/27207059/firebase-query-double-nested – Frank van Puffelen May 04 '18 at 02:46
  • OK, am able to know my own UID, just the other party I couldnt find a way to get it from swift. will be thinking about it.. – William Loke May 04 '18 at 02:51