【问题标题】:Chaining getDocument with Firestore?将 getDocument 与 Firestore 链接?
【发布时间】:2017-11-26 19:38:53
【问题描述】:
user
  29384092840923
     chatRoomsJoined
         chatRoom1
         chatroom5

chatrooms
   chatRoom1 
      users 
         29384092840923
         298340982039490

我正在尝试加载一个表格视图,其中包含有关用户加入的聊天室的信息。在上述情况下,用户“29384092840923”已加入 chatRoom1,我需要 chatRoom1 中用户节点的子节点数

我最初的策略是从“用户”节点获取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 的调度组似乎是错误的。

【问题讨论】:

    标签: ios swift firebase google-cloud-firestore


    【解决方案1】:

    一种可能的选择是使用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() 调用正确,否则你会遇到一些非常奇怪的崩溃。

    【讨论】:

    • 非常感谢克里斯。欣赏!
    猜你喜欢
    • 2020-07-24
    • 1970-01-01
    • 2021-05-01
    • 2019-11-13
    • 2019-06-27
    • 2018-10-16
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    相关资源
    最近更新 更多