如何异步观察Firebase节点?现在,一旦观察到节点中的所有子节点,我就使用DispatchGroup来关闭一个闭包。
我想在这个节点上保留一个监听器,因为我希望将来会改变这些值。
如果我使用dispatchGroup,数据库中的更新会导致dispatchGroup.leave()触发,而没有相应的.enter()导致我的应用程序崩溃。这是我的代码:
func fetchPosts(completion: @escaping ([Post]) -> Swift.Void) {
let dispatchGroup = DispatchGroup()
guard let uid = Auth.auth().currentUser?.uid else { return }
let dbRef = Database.database().reference()
let userPosts = dbRef.child("user-posts")
let postRef = dbRef.child("posts")
userPosts.child(uid).observe(.value, with: { (snap) in
if let dictionary = snap.value as? [String:Any] {
for item in dictionary {
dispatchGroup.enter()
postRef.child(item.key).observe(.value, with: { (snap) in
if let dictionary = snap.value as? [String:Any] {
let newPost = Post(dictionary: dictionary)
self.posts.append(newPost)
dispatchGroup.leave()
}
})
}
}
dispatchGroup.notify(queue: DispatchQueue.main) {
completion(self.posts)
}
})
}