无法使DispatchGroup在Swift中正常工作

时间:2018-02-14 16:25:01

标签: ios swift rest alamofire

在更新UI之前需要等待一些api调用循环才能完成,但是在http调用之前还无法找到我的DispatchGroup.notify()执行的原因:

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)
            }
        }

    }
}

有人在这里有一些提示吗? 提前谢谢!

1 个答案:

答案 0 :(得分:3)

您的问题是您在错误的地方致电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更新。