0

我正在尝试更新多个集合,下面的代码仅在数组中的最后一项上访问 getDocument,我试图通过将 getDocument 放入新函数并使用完成处理程序和 dispatchGroup 来解决该问题。

    pp.order .forEach {singleOrder in
        let dispatchGroup = DispatchGroup()
        let zz = Order.init(data: singleOrder)

        if (zz.isH == true){

            let ww = db.collection("oo").document(zz.ComRefParentID)
            dispatchGroup.enter()

            ww.getDocument { (snap, error) in
                guard let data = snap?.data() else { return}
                let orderCpm = data["order"] as? [[String: Any]]

                var uu:[[String : Any]] = []

                var counter = 0

                while(counter < orderCpm!.count){

                    let newArrayElement = OrderC.init(data: orderCpm![counter])

                    if(newArrayElement.ComRef == zz.ComRef){

                        let isOffered = newArrayElement.isOffered
                        let ComRef = newArrayElement.ComRef
                        let isAcc = true
                        let isActive = false
                        let theO = newArrayElement.theO

                        let editedElement = OrderC.init(ComRef: ComRef, theO: theO, isOffered: isOffered, isAcc: isAcc, isActive: isActive)

                        let toAdd = OrderC.modelToData(user: editedElement)
                        uu.append(toAdd)
                    }else{
                        let toAdd = OrderC.modelToData(user: newArrayElement)
                        uu.append(toAdd)
                    }
                    counter += 1
                }

                ww.updateData([
                    "order": uu
                ]) { err in
                    if let err = err {
                        print("Error updating document: \(err)")
                    } else {
                        dispatchGroup.leave()
                        print("Document successfully updated")
                    }
                }
            }
        }
    }
}
4

0 回答 0