I need only run the code after requesting several HTTP resources to collect some data.
I read a lot of documentation and I found out that I have to use GCD and sending groups:
- Create a group with
dispatch_group_create() - For each request:
- Enter the dispatch group with
dispatch_group_enter() - Run request
- When you receive a response, leave the group with
dispatch_group_leave()
- Wait with
dispatch_group_wait() - Release the group with
dispatch_release()
But I'm not sure that this practice may have some pitfalls - or is there a better way to wait for parallel requests to be completed?
The code below looks good:
func sendRequest(url: String, whenFinished: () -> Void) {
let request = NSMutableURLRequest(URL: NSURL(string: url))
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {
(data, response, error) -> Void in
whenFinished()
})
task.resume()
}
let urls = ["http://example.com?a",
"http://example.com?b",
"http://example.com?c",
"http://example.com?d",
"http://invalid.example.com"]
var fulfilledUrls: Array<String> = []
let group = dispatch_group_create();
for url in urls {
dispatch_group_enter(group)
sendRequest(url, {
() in
fulfilledUrls.append(url)
dispatch_group_leave(group)
})
}
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
for url in fulfilledUrls { println(url) }
source
share