gpt4 book ai didi

ios - 嵌套请求的完成 block

转载 作者:行者123 更新时间:2023-11-30 11:09:50 25 4
gpt4 key购买 nike

我正在尝试为嵌套请求构建带有完成 block 的方法。问题在于,完成 block 提前捕获了父请求(这意味着子请求尚未实际完成)。到目前为止,除了我在下面的示例中所做的之外,我还没有找到一种方法让子请求与父请求进行通信(即计算已完成的子请求数量并将其与预期数量进行比较)请求数)。

下面的示例针对 Firestore 数据库进行操作。想象一下,用户有多个纸牌游戏(牌组),每个游戏都有多张牌。我非常感谢您为如何为此类案例构建更好的完成 block 提供的任何帮助:

func fetchCardsCount(uid: String, completion: @escaping (Int) -> ()) {
let db = Firestore.firestore()


var decksCount = Int()
var cardsCount = Int()

db.collection("users").document(uid).collection("decks").getDocuments { (deckSnapshot, err) in
if let err = err {
print("Error fetching decks for user: ", err)
} else {
guard let deckSnapshot = deckSnapshot else { return }

deckSnapshot.documents.forEach({ (deck) in
let dictionary = deck.data() as [String: Any]
let deck = FSDeck(dictionary: dictionary)
db.collection("users").document(uid).collection("decks").document(deck.deckId).collection("cards").getDocuments(completion: { (cardSnapshot, err) in
if let err = err {
print("Error fetching cards for deck: ", err)
} else {
guard let cardSnapshot = cardSnapshot else { return }
decksCount += 1
cardsCount += cardSnapshot.count

if decksCount == deckSnapshot.count {
completion(cardsCount)
}
}
})
})
}
}
}

最佳答案

这是使用 DispatchGroup 的解决方案,在评论中通过 @meggar 的帮助找到:

func fetchCardsCount(uid: String, completion: @escaping (Int) -> ()) {
let db = Firestore.firestore()

var cardsCount = Int()
let group = DispatchGroup()

group.enter()
db.collection("users").document(uid).collection("decks").getDocuments { (deckSnapshot, err) in
if let err = err {
print("Error fetching decks for user: ", err)
} else {
guard let deckSnapshot = deckSnapshot else { return }

deckSnapshot.documents.forEach({ (deck) in
let dictionary = deck.data() as [String: Any]
let deck = FSDeck(dictionary: dictionary)

group.enter()
db.collection("users").document(uid).collection("decks").document(deck.deckId).collection("cards").getDocuments(completion: { (cardSnapshot, err) in
if let err = err {
print("Error fetching cards for deck: ", err)
} else {
guard let cardSnapshot = cardSnapshot else { return }
cardsCount += cardSnapshot.count
}
group.leave()
})
})
}
group.leave()
}

group.notify(queue: .main) {
completion(cardsCount)
}
}

关于ios - 嵌套请求的完成 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52297728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com