簡體   English   中英

通過循環 SWIFT 延遲將數據刪除到 Firestore 數組字段值中

[英]Delay of delete data into Firestore array field values through loop SWIFT

在此處輸入圖片說明

我正在嘗試通過這樣的 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()
            }
        }
    }

和 Firebase 管理器:

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 上的所有購物車項目然后加載它們? 非常感謝。

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)
         }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM