gpt4 book ai didi

ios - 无法让 DispatchGroup 在 Swift 中正常工作

转载 作者:行者123 更新时间:2023-11-28 10:45:15 24 4
gpt4 key购买 nike

在更新 UI 之前需要等待一些 api 调用循环完成,但还不能找出为什么我的 DispatchGroup.notify() 在 http 调用之前被执行:

override func viewDidAppear(_ animated: Bool) {

if isFirstLoad {

ProgressIndicator.shared.showProgressView(self.view)

let serviceUrl = MobnerServices.service_base+"GetTrainersAround?lat=\(self.currLatitude!)&lon=\(self.currLongitude!)&radius=50"

Alamofire.request(serviceUrl).responseJSON{ response in
do{
guard let responseData = response.data else{
print("No data received.")
ProgressIndicator.shared.hideProgressView()
return
}

let dispatchGroup = DispatchGroup()
let decoder = JSONDecoder()

let retrievedTrainers = try decoder.decode([STTrainer].self, from: responseData)

self.trainers = retrievedTrainers
self.isFirstLoad = false

for trainer in self.trainers{
dispatchGroup.enter()

let getUserPictureUrl = MobnerServices.service_base+"GetUserPicture?filename=\(trainer.profilePicturePath)"

Alamofire.request(getUserPictureUrl).responseImage { response in
guard let image = response.result.value else {
print(response.error!.localizedDescription)
return
}

self.trainersPictures.append(STTrainerPicture(userId: trainer.userId, profilePicture: image))
}

dispatchGroup.leave()
}

dispatchGroup.wait()

ProgressIndicator.shared.hideProgressView()
self.tableView.reloadData()

}
catch{
print(error.localizedDescription)
}
}

}
}

有人有什么建议吗?提前致谢!

最佳答案

您的问题是您在错误的地方调用了 dispatchGroup.leave()。它需要在异步调用的完成处理程序中。

let dispatchGroup = DispatchGroup()
let decoder = JSONDecoder()

let retrievedTrainers = try decoder.decode([STTrainer].self, from: responseData)

self.trainers = retrievedTrainers
self.isFirstLoad = false

for trainer in self.trainers{
dispatchGroup.enter()

let getUserPictureUrl = MobnerServices.service_base+"GetUserPicture?filename=\(trainer.profilePicturePath)"

Alamofire.request(getUserPictureUrl).responseImage { response in
guard let image = response.result.value else {
print(response.error!.localizedDescription)
dispatchGroup.leave()
return
}

self.trainersPictures.append(STTrainerPicture(userId: trainer.userId, profilePicture: image))
dispatchGroup.leave()
}
}

dispatchGroup.notify(queue: .main) {
ProgressIndicator.shared.hideProgressView()
self.tableView.reloadData()
}

您还需要在主队列上执行 UI 更新。

关于ios - 无法让 DispatchGroup 在 Swift 中正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48791838/

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