Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
700 views
in Technique[技术] by (71.8m points)

ios - Count unseen messages with Firebase in Swift

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...