如何知道Firebase何时使用Swift完成快照中所有节点的下载?

时间:2019-06-25 00:44:57

标签: swift firebase-realtime-database

我具有以下功能,可从messages获取Firebase,我想知道Firebase何时完成了数据snapshot的所有子节点的加载,因此我可以通过handler返回一个信号,表明所有数据已完成加载。

func loadLatestChatConversationMessages(forUserId forId: String!, handler: @escaping (Message?) -> ()){

    guard let uid = Auth.auth().currentUser?.uid else {return}

    let ref = REF_USERS_MESSAGES.child(uid).child(forId)

    let firstBatchCount: Int = 12

       RefUserMessagesChatConvoHandle = ref.queryOrderedByKey().queryLimited(toLast: UInt(firstBatchCount)).observe(.value, with: { (snapshot) in


            if snapshot.childrenCount > 0 {

                for child in snapshot.children.allObjects as! [DataSnapshot]{

                    let key = child.key


                    self.REF_MESSAGES.child(key).observeSingleEvent(of: .value, with: { (snapshot) in


                        guard var dictionary = snapshot.value as? [String : Any] else { return }

                        dictionary["messageId"] = key

                        let message = Message(dictionary: dictionary)

                        handler(message)

                    }, withCancel: nil)


                }//end for


            } else {
                print("returning - no messages.")
                handler(nil)

            }// end if snapshot.childrenCount

        }, withCancel: nil)


}//end func

1 个答案:

答案 0 :(得分:0)

在顶部创建一个dispatchGroup对象,并立即输入enter()。 https://developer.apple.com/documentation/dispatch/dispatchgroup

let dg = DispatchGroup()

,然后在每个子下载中,您要输入enter()并在完成后离开()。

然后您最终致电

dg.notify(queue: .main, work: {
    // escape the close
})