How do I know when iOS concurrent HTTP requests are made?

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:

    // Just send a request and call the when finished closure
    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) }
+4
source share
1

Yup, , dispatch_group_notify dispatch_group_wait, dispatch_group_wait , , dispatch_group_notify , .

+3

All Articles