Concurrent API Calls in Swift

This post shows an example of how to make multiple asynchronous HTTP requests at the same time in Swift.

For examples and more details on how to make an HTTP request in Swift, check out: GET and POST HTTP Requests in Swift without Alamofire.

Create a DispatchGroup

Use a DispatchGroup to keep track of multiple asynchronous tasks.

// Create a dispatch group
let group = DispatchGroup()

let urls = [
    URL(string: /* API endpoint 1 */),
    URL(string: /* API endpoint 2 */),
    URL(string: /* API endpoint 3 */),
]

Make HTTP Requests In Parallel

When a new task starts, call group.enter(). When a task ends, call group.leave(). Always make sure to call group.leave() when a task completes.

// Make multiple simultaneous requests
for url in urls {
    group.enter()
    get(url: url) { (data, error) in
        // Process data, error
        group.leave()
    }
}

Configure A Completion Callback

When all tasks complete the DispatchGroup trigger a callback. Here, the .main queue is specified indicating that the callback block should be called on the main thread.

// Configure a completion callback
group.notify(queue: .main) {
    // All requests completed
}

Multiple, Asynchronous HTTP Requests

That’s it! With the DispatchGroup you can make concurrent API requests in Swift.