我正在尝试通过URLSession.shared单例实现许多并发api调用。我想要的是它们是同时进行的,所以当我收到所有响应时,然后执行完成处理程序(我以这个示例为例:https://medium.com/@oleary.audio/simultaneous-asynchronous-calls-in-swift-9c1f5fd3ea32):
init(completion: (()->Void)? = nil) throws {
self.myToken = myToken
let group = DispatchGroup()
group.enter()
print("Downloading User")
self.downloadUser(completion: { userObject in
self.userObject = userObject
group.leave()
})
group.enter()
print("Downloading Tickets")
self.downloadTickets(completion: { ticketsObject in
if let ticketsObject = ticketsObject {
self.ticketsObject = ticketsObject
}
group.leave()
})
group.wait()
completion?()
}
然后实现api调用的函数如下:
private func downloadUser( completion: @escaping ((myUsuario)->Void )) {
let url = URL(string: "\(Globals.laravelAPI)me")
var request = URLRequest(url: url!)
let task = URLSession.shared.dataTask(with: request) {
(data:Data?, response:URLResponse?, error:Error?) in
if let error = error {
...
}
guard let httpResponse = response as? HTTPURLResponse,(200...299).contains(httpResponse.statusCode) else { ... }
if let data = data {
do {
let user = try JSONDecoder().decode(myUsuario.self, from: data)
completion(user)
} catch {
print("USER PARSING ERROR: \(error)")
fatalError()
}
}
}
task.resume()
}
当我运行该程序时,它会进行调用,但从未得到响应,因此group.wait()
从未执行。