【发布时间】:2018-07-19 02:18:13
【问题描述】:
我正在使用 DispatchGroup 等到我的一个函数的回调执行后再继续。在该函数中,我调用了 Alamo fire get 请求。我的问题是在我引入 DispatchGroup 时出现的,AlamoFire 闭包永远不会被执行。
样本
let group = DispatchGroup()
group.enter()
Networking.getInfo(userID: userID) { info in
group.leave()
}
group.wait()
Networking类:
static func getInfo(userID: Int, completion: @escaping(_ info: String) -> Void) {
// Program reaches here
Alamofire.request("https://someurl.com").responseJSON { response in
// Program does NOT get here
if let json = response.result.value {
completion("Successful request")
} else {
completion("Some Error")
}
}
}
当我不使用 DispatchGroup 时,它可以正常工作。当我使用 DispatchGroup 时,getInfo 函数会启动,但 Alamofire 请求的关闭永远不会执行。
【问题讨论】:
-
试图将异步操作转换为同步操作是错误的方法。
-
调度组不是等待操作完成的选择。您可能需要 Semaphore 。但是这样你可能会陷入僵局
标签: ios swift alamofire grand-central-dispatch