Created
June 23, 2018 17:41
-
-
Save novinfard/0feffe67b78bb1131234ee6c91f3ff06 to your computer and use it in GitHub Desktop.
[Working with multiple tasks in GCD]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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