由于循环,Swift 完成处理程序 For 循环将执行一次而不是 10 次

标签 swift loops for-loop google-cloud-firestore completionhandler

我有一个循环,其中包含一个重复 10 次的 firestore 查询。我需要在所有 10 个查询完成后调用 (completion: block) ;在这里,我有我的代码,以便它执行(完成:阻止)每个查询,但这对服务器和用户的手机来说太重了。我如何更改下面的内容以完成我刚刚描述的内容?

static func getSearchedProducts(fetchingNumberToStart: Int, sortedProducts: [Int : [String : Int]], handler: @escaping (_ products: [Product], _ lastFetchedNumber: Int?) -> Void) {

        var lastFetchedNumber:Int = 0
        var searchedProducts:[Product] = []

        let db = Firestore.firestore()

        let block : FIRQuerySnapshotBlock = ({ (snap, error) in

            guard error == nil, let snapshot = snap else {
                debugPrint(error?.localizedDescription)
                return
            }

            var products = snapshot.documents.map { Product(data: $0.data()) }

            if !UserService.current.isGuest {

                db.collection(DatabaseRef.Users).document(Auth.auth().currentUser?.uid ?? "").collection(DatabaseRef.Cart).getDocuments { (cartSnapshot, error) in
                    guard error == nil, let cartSnapshot = cartSnapshot else {
                        return
                    }

                    cartSnapshot.documents.forEach { document in
                        var product = Product(data: document.data())
                        guard let index = products.firstIndex(of: product) else { return }
                        let cartCount: Int = document.exists ? document.get(DatabaseRef.cartCount) as? Int ?? 0 : 0
                        product.cartCount = cartCount
                        products[index] = product
                    }
                    handler(products, lastFetchedNumber)
                }
            }

            else {
                handler(products, lastFetchedNumber)
            }
        })

        if lastFetchedNumber == fetchingNumberToStart {

            for _ in 0 ..< 10 {

                //change the fetching number each time in the loop
                lastFetchedNumber = lastFetchedNumber + 1

                let productId = sortedProducts[lastFetchedNumber]?.keys.first ?? ""

                if productId != "" {
                    db.collection(DatabaseRef.products).whereField(DatabaseRef.id, isEqualTo: productId).getDocuments(completion: block)
                }
            }
        }

    }

正如你在最后看到的,由于 for _ in 0 ..< 10,我为此查询循环了 10 次。 :
if productId != "" {
                    db.collection(DatabaseRef.products).whereField(DatabaseRef.id, isEqualTo: productId).getDocuments(completion: block)
                }

所以我需要制作 completion: block处理程序在这里只被调用一次而不是 10 次。

最佳答案

使用 DispatchGroup .您可以在每次调用异步代码时进入调度组,然后每次完成后离开。然后当一切都完成后,它会调用通知块,你可以调用你的处理程序。下面是一个简单的例子:

let dispatchGroup = DispatchGroup()
let array = []

for i in array {
    dispatchGroup.enter()
    somethingAsync() {
        dispatchGroup.leave()
    }
}

dispatchGroup.notify(queue: .main) {
    handler()
}

关于由于循环,Swift 完成处理程序 For 循环将执行一次而不是 10 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61165286/

相关文章:

ios - Swift UIImageView 拉伸(stretch)方面

javascript - 是否可以反转 for 循环

ios - 将PhysicsBody 与SKShapenode 线结合使用。 swift 、iOS、SpriteKit

swift - 以编程方式将按钮放在一起

python - 使用 Python 从文件中查找多个最大值

c++ - 我正在计算的序列(冰雹)在需要打印一次时打印两次

python - 如何将指定的键+值移动到另一个字典

jquery - 使用 for 循环和 jquery 加载事件处理多个图像仅返回最后加载的一个 props

php - 修改php oop mysql查询

ios - SQLite.swift:实现表示给定表行的模型类的最佳方式?