title: Count unseen messages with Firebase in Swift
body: <p>I'm trying to code a chat app.</p>
  
  <p>I would like to count the number of messages, which are not viewed (unseen). </p>
  
  <p>My database looks like this:</p>
  
  <pre><code>user-messages
   |
   |_messages
      |
      |_UserID1
      |   |
      |   |_UserID2
      |     |
      |     |_ MessageID1
      |     |_ MessageID2
      |     |_ MessageID3
      |     |_ etc...
      |     
      |_UserID2
      |   |
      |   |_UserID1
      |     |
      |     |_ MessageID1
      |     |_ MessageID2
      |     |_ MessageID3
      |     |_ etc...
  </code></pre>
  
  <p>And for the Messages object:</p>
  
  <pre><code>messages
   |
   |_messageID1
   |  |
   |  |_ notViewed: false / true
   |  |_ text: "Message text"
   |  |_ timestamp: 1522230692
   |  |_ etc...
   |  
   |_messageID2
   |  |
   |  |_ notViewed: false / true
   |  |_ text: "Message text"
   |  |_ timestamp: 1522230692
   |  |_ etc...
  </code></pre>
  
  <p>I arrived to get all the message ID which are linked to a specific user:</p>
  
  <pre><code>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) -&gt; 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)
                  })
               })
            }
      }
  </code></pre>
  
  <p>But I don't know what I need to do with that list, to observe the number of unseen messages ...</p>
  
  <p>I tried that, but without success:</p>
  
  <pre><code>func fetchMessageNotViewed(_ messageId: String, completion: @escaping (Int) -&gt; 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)
  }
  </code></pre>