ios - 将 getDocument 与 Firestore 链接起来?

标签 ios swift firebase google-cloud-firestore

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/

相关文章:

ios - 如果 URL 快速失败,如何为 AVPlayer 重新加载数据

ios - 应用程序加载器错误 ITMS-90062 : The value for key CFBundleShortVersionString must contain a higher version

Swift 中带有普通和粗体文本标签的 iOS 选择器 View

ios - 当应用程序切换器出现时,执行命令 Xcode swift

firebase - 如何防止Firestore中不必要的文档读取?

objective-c - iOS vsnprintf 使用 NSString 实现

ios - 如何知道 enumerateTags 函数何时完成?

swift - 如何突出显示每个段落并使用 speechSynthesizer 滚动 textView

Firebase 函数不提供函数 URL

javascript - 使用 React 和 Axios 更新 Firebase 中的数据