Yassir
Yassir

Reputation: 61

NSURLSession tasks run in for loop

I'm trying to use an NSURLSession to load multiple requests in a for loop.

for id in ids{
    // ids is an Array of String
    let url = NSURL(string:"http://example.com/something?ID=\(id)")   
    //                                                     ^ 
    NSURLSession.sharedSession().dataTaskWithURL(url!){(data, response, error)in
        if error2 != nil {
            print(error2)
            return
        }
        do{
            let strjson = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers)

            // Here is the problem the for loop doesn't let enough time to the NSURLSession
        }catch let errorjson {
            print(errorjson)
        }
    }.resume 
}

Upvotes: 1

Views: 975

Answers (1)

Code Different
Code Different

Reputation: 93141

Here's one approach using Grand Central Dispatch:

let urls = ids.map { NSURL(string:"http://example.com/something?ID=\($0)")! }

let group = dispatch_group_create()

// Loop through the urls array, in parallel
dispatch_apply(urls.count, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0)) { i in

    // Tell GCD that you are starting a new task
    dispatch_group_enter(group)

    NSURLSession.sharedSession().dataTaskWithURL(urls[i]) { data, response, error in
        // Do your thing....

        // Tell GCD you are done with a task
        dispatch_group_leave(group)
    }.resume()
}

// Wait for all tasks to complete. Avoid calling this from the main thread!!!
dispatch_group_wait(group, DISPATCH_TIME_FOREVER)

// Now all your tasks have finished

Upvotes: 6

Related Questions