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()
}
}
}
和Firebasemanr:
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)
}
}