ios 通过循环SWIFT将数据删除到Firestore阵列字段值的延迟

omqzjyyz  于 2023-03-05  发布在  iOS
关注(0)|答案(1)|浏览(114)

我正尝试通过一个for循环删除所有购物车项目,如下所示:

func removeRelatedProductFromUserCart(selectArrayNodeIds: [String], completion: @escaping(Error?)->()) {
        let semaphore = DispatchSemaphore(value: 0)
        let serialQueue = DispatchQueue(label: "com.queue.Serial")
        
        serialQueue.async {
            for nodeId in selectArrayNodeIds {
                FirebaseManager.shared.removeProductFromUsersWishOrCartList(isForWishList: false, item: nodeId) { (error) in
                    completion(error)
                    semaphore.signal()
                }
                semaphore.wait()
            }
        }
    }

和Firebasemanager:

func removeProductFromUsersWishOrCartList(isForWishList: Bool, item: String?, completion: @escaping (Error?) -> ()) {
        let uid = UserDefaults.standard.string(forKey: "uid")!
        if isForWishList == true {
            Firestore.firestore().collection("user").document(uid).updateData([
                "wishList": FieldValue.arrayRemove([item!])
            ]) { (error) in
                completion(error)
            }
        } else {
            Firestore.firestore().collection("user").document(uid).updateData([
                "cart": FieldValue.arrayRemove([item!])
            ]) { (error) in
                completion(error)
            }
        }
    }

然后当我试图从同一字段中获取购物车项目时,我在延迟后获得更新的购物车项目列表。我观察了删除过程打开firebase控制台,我发现删除在控制台中发生延迟。但错误响应(error == nill)removeRelatedProductFromUserCart中没有等到那时。那么,我如何等到删除Firestore上的所有购物车项目,然后加载它们?

6mzjoqzu

6mzjoqzu1#

1-Firebase在后台线程中运行,因此无需

let serialQueue = DispatchQueue(label: "com.queue.Serial")

2-你需要一个DispatchGroup

func removeRelatedProductFromUserCart(selectArrayNodeIds: [String], completion: @escaping(Bool)->()) {

           let g = DispatchGroup() 
            for nodeId in selectArrayNodeIds {
                 g.enter()
                 FirebaseManager.shared.removeProductFromUsersWishOrCartList(isForWishList: false, item: nodeId) { (error) in  
                   q.leave()
                } 
            } 
         g.notify(queue:.main) {
            completion(true)
         }
}

相关问题