Skip to content

Instantly share code, notes, and snippets.

@novinfard
Created June 23, 2018 17:41
Show Gist options
  • Save novinfard/0feffe67b78bb1131234ee6c91f3ff06 to your computer and use it in GitHub Desktop.
Save novinfard/0feffe67b78bb1131234ee6c91f3ff06 to your computer and use it in GitHub Desktop.
[Working with multiple tasks in GCD]
let myGroup = DispatchGroup()
var result = [Data]()
for i in 0 ..< 5 {
myGroup.enter()
Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"]).responseJSON { response in
print("Finished request \(i)")
result.append(response.data)
myGroup.leave()
}
}
// Synchronously with timer (10 seconds)
myGroup.wait(timeout: DispatchTime(uptimeNanoseconds: 10000000000))
// Asynchronously without timer
myGroup.notify(queue: .main) {
return result
}
// Synchronousely with timer
myGroup.notifyWait(target: .main,
timeout: DispatchTime.now() + 10) {
return result
}
extension DispatchGroup {
func notifyWait(target: DispatchQueue, timeout: DispatchTime, handler: @escaping (() -> Void)) {
DispatchQueue.global(qos: .default).async {
_ = self.wait(timeout: timeout)
target.async {
handler()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment