gpt4 book ai didi

ios - 如何在一个函数中运行 2 个异步代码并转义它们?

转载 作者:行者123 更新时间:2023-11-28 23:35:46 25 4
gpt4 key购买 nike

我想在一个函数中运行 2 段异步代码并转义它们。我想先下载 Reciter 信息,然后使用这些信息下载与 Reciter 关联的图像。我正在使用 Firestore。我尝试使用 DispatchQueue 和 DispatchGroup,但我无法弄清楚。我希望有人能帮助我:)

func getReciters(completion: @escaping (Bool) -> Void) {
var reciters = [Reciter]()
self.BASE_URL.collection(REF_RECITERS).getDocuments { (snapchot, error) in
if let error = error {
debugPrint(error)
completion(false)
// TODO ADD UIALTERCONTROLLER MESSAGE
return
}

guard let snapchot = snapchot else { debugPrint("NO SNAPSHOT"); completion(false); return }

for reciter in snapchot.documents {
let data = reciter.data()
let reciterName = data[REF_RECITER_NAME] as? String ?? "ERROR"
let numberOfSurahs = data[REF_NUMBER_OF_SURAHS] as? Int ?? 0

// **HERE I WANT TO DOWNLOAD THE IMAGES**
self.downloadImage(forDocumentID: reciter.documentID, completion: { (image) in
let reciter = Reciter(name: reciterName, image: nil, surahCount: numberOfSurahs, documentID: reciter.documentID)
reciters.append(reciter)
})
}
}
UserDefaults.standard.saveReciters(reciters)
completion(true)
}

最佳答案

您需要 DispatchGroup

  • 在函数范围内声明一个 DispatchGroup 的实例。
  • 在循环之前异步 block 调用enter
  • 在循环内部异步 block 调用的完成处理程序离开
  • 在循环调用notify之后,闭包将在所有异步任务完成后执行。

func getReciters(completion: @escaping (Bool) -> Void) {
var reciters = [Reciter]()
self.BASE_URL.collection(REF_RECITERS).getDocuments { (snapchot, error) in
if let error = error {
debugPrint(error)
completion(false)
// TODO ADD UIALTERCONTROLLER MESSAGE
return
}

guard let snapchot = snapchot else { debugPrint("NO SNAPSHOT"); completion(false); return }
let group = DispatchGroup()

for reciter in snapchot.documents {
let data = reciter.data()
let reciterName = data[REF_RECITER_NAME] as? String ?? "ERROR"
let numberOfSurahs = data[REF_NUMBER_OF_SURAHS] as? Int ?? 0
group.enter()

self.downloadImage(forDocumentID: reciter.documentID, completion: { (image) in
let reciter = Reciter(name: reciterName, image: nil, surahCount: numberOfSurahs, documentID: reciter.documentID)
reciters.append(reciter)
group.leave()
})
}
group.notify(queue: .main) {
UserDefaults.standard.saveReciters(reciters)
completion(true)
}
}
}

关于ios - 如何在一个函数中运行 2 个异步代码并转义它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55034480/

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