I'm trying to code a chat app.
I would like to count the number of messages, which are not viewed (unseen).
My database looks like this:
user-messages
|
|_messages
|
|_UserID1
| |
| |_UserID2
| |
| |_ MessageID1
| |_ MessageID2
| |_ MessageID3
| |_ etc...
|
|_UserID2
| |
| |_UserID1
| |
| |_ MessageID1
| |_ MessageID2
| |_ MessageID3
| |_ etc...
And for the Messages object:
messages
|
|_messageID1
| |
| |_ notViewed: false / true
| |_ text: "Message text"
| |_ timestamp: 1522230692
| |_ etc...
|
|_messageID2
| |
| |_ notViewed: false / true
| |_ text: "Message text"
| |_ timestamp: 1522230692
| |_ etc...
I arrived to get all the message ID which are linked to a specific user:
var REF_MESSAGE = Database.database().reference().child("messages")
var REF_USER_MESSAGE = Database.database().reference().child("user-messages").child("messages")
func fetchUnviewedMessages(withId id: String, completion: @escaping (Int) -> Void ) {
REF_USER_MESSAGE.child(id).observe(.childAdded) { (snapshot) in
let userId = snapshot.key as String
self.REF_USER_MESSAGE.child(id).child(userId).observe(.childAdded, with: { (snapshot) in
let messageId = snapshot.key
// This part is where I have a problem
self.fetchMessageNotViewed(messageId, completion: { (nbMessageNotRead) in
completion(nbMessageNotRead)
})
})
}
}
But I don't know what I need to do with that list, to observe the number of unseen messages ...
I tried that, but without success:
func fetchMessageNotViewed(_ messageId: String, completion: @escaping (Int) -> Void) {
guard let currentUid = Api.User.CURRENT_USER?.uid else {
return
}
REF_MESSAGE.child(messageId).queryOrdered(byChild: "notViewed").queryEqual(toValue: true).observe(.value, with: { (snapshot) in
let count = Int(snapshot.childrenCount)
print(count)
}, withCancel: nil)
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…