Swift中,如何等到多个回调都完成后再执行

var myGroup = DispatchGroup()

override func viewDidLoad() {
    super.viewDidLoad()

    for i in 0 ..< 5 {
        myGroup.enter()

        Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"]).responseJSON { response in
            print("Finished request \(i)")
            self.myGroup.leave()
        }
    }

    myGroup.notify(queue: .main) {
        print("Finished all requests.")
    }
}

有点类似于Java中的栅栏,但是好用很多,有木有~

Leave a Reply

Your email address will not be published. Required fields are marked *