iOS - swift 3 - DispatchGroup

南笙酒味 提交于 2019-12-02 06:12:44

I think you need to put self.dispatchGroup.leave() inside the Alamofire response handler. As written, you leave as soon as you queue the request.

    queue.async(group: dispatchGroup) {
        Alamofire.request(Content.url).responseJSON { response in
            switch response.result {
            case .success(let value):
                let json = JSON(value)
                // do some stuff and save to Content struct
                Content.annotations += [Station(...)]

            case .failure(let error):
                print("error: ",error)
            }
            self.dispatchGroup.leave()
        }
    }

Change your code as shown below.

public func getData() {
    dispatchGroup.enter()
    queue.async(group: dispatchGroup) {
        Alamofire.request(Content.url).responseJSON { response in
            switch response.result {
            case .success(let value):
                let json = JSON(value)
                // do some stuff and save to Content struct
                Content.annotations += [Station(...)]

            case .failure(let error):
                print("error: ",error)
            }
            self.dispatchGroup.leave() // This statement has been moved
        }
    }
}

The mistake was that you were leaving the DispatchGroup soon after you entered it. If you have to wait for your network operation to complete, you should leave from within the response handler.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!