user
29384092840923
chatRoomsJoined
chatRoom1
chatroom5
chatrooms
chatRoom1
users
29384092840923
298340982039490
我正在尝试加载一个 TableView ,其中包含有关用户加入的聊天室的信息。在上面的例子中,用户“29384092840923”已经加入了 chatRoom1,我需要 chatRoom1 中 users 节点的 child 的数量
我最初的策略是从“用户”节点获取一个 joinedChatRooms 数组,然后执行 for 循环并对数组中的每个项目执行 getDocument。
static func loadFavoriteRooms(forUID uid: String, completedFetch: @escaping (_ favoritedRoomsArray : [String]?, _ error : Error?)->()) {
let userFavoritesRef = database.collection("users").document(uid).collection("favoritedRooms")
userFavoritesRef.getDocuments { (snapshot, error) in
if error != nil {
completedFetch(nil, error!)
print("There was an error", error!.localizedDescription)
} else {
var roomArray = [String]()
for document in snapshot!.documents {
//Create a roomRef with the documentID, do a getDocument with it, and create an object with it?
let roomName = document.documentID
roomArray.append(roomName)
}
completedFetch(roomArray, nil)
}
}
}
我对上面发生的事情的问题是,一旦我开始在 for 循环中为各个 roomRefs 发送额外的 getDocument 请求,我的 completedFetch 完成调用在 for 循环异步完成之前返回,我没有得到填充数组返回。
最简洁的方法是什么?我需要在这里做一个调度组还是有更好的方法来完成这个?出于某种原因,在我看来,将调度组与 firestore 一起使用似乎是错误的。
最佳答案
一个可能的选择是使用 DispatchGroup .像-
var roomArray = [String]()
let dispatchGroup = DispatchGroup()
for document in snapshot!.documents {
let roomId = document.documentID
let roomRef = database.collection("rooms").document(roomId)
dispatchGroup.enter()
roomRef.getDocument { (roomSnapshot, error) in
// Create the room from the snapshot here
roomArray.append(roomName)
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: .main, execute: {
completedFetch(roomArray, nil)
})
只需确保您的 .enter()
和 .leave()
调用正确,否则您会遇到一些非常奇怪的崩溃。
关于ios - 将 getDocument 与 Firestore 链接起来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47500218/