Firebase with Swift 3 counting the number of children

前端 未结 3 834
遥遥无期
遥遥无期 2020-12-10 09:02

I have an array of strings and I am trying to populate it through firebase. It is a chat application and when a user creates a room he or she names the room. When the user l

3条回答
  •  一向
    一向 (楼主)
    2020-12-10 09:25

    Firebase data is loaded (and synchronized) asynchronously. This is easiest to see if you add some debug logging:

    let ref = firebase.child("users").child(fUID).child("participating")
    
    print("Starting observing");
    ref.observe(.value, with: { (snapshot: FIRDataSnapshot!) in
        print("Got snapshot");
        print(snapshot.childrenCount)
        rooms.count = snapshot.childrenCount
    })
    
    print("Returning count");
    return rooms.count
    

    When you run this snippet, the logging output will be:

    Start observing

    Returning count

    Got snapshot

    This is probably not the order you expected the output to be in. And it also explains why your count will never be correct: the data hasn't been loaded yet, so it can't be counted.

    This is the reason why Firebase listeners work with callback blocks: the block is invoked when the data is synchronized.

提交回复
热议问题