Making async calls using URLSession.shared.data

The Combine Framework enables asynchronous programming but now we have URLSession.shared.data which was introduced in iOS 15 that enables for easier to read and write concurrent code. For example, below we can make a series of API calls in line and upon all being successful update our UI or another task we need to accomplish.

URLSession.shared.data is Available in 15+

// Inside the API class 
// Note: mark this class with `@MainActor` for work to be 
// dispatched to the `main` thread when updated the UI
let (data, _) = try await URLSession.shared.data(from: url)
let items = try JSONDecoder().decode(ItemWrapper.self, from: data)

// Using the API class to make asynchronous calls
let firstAsycnCall = try await API.firstRequest(for: itemOne)
let secondAsycnCall = try await API.secondRequest(for: itemTwo)
let thirdAsycnCall = try await API.thirdRequest(for: itemThree)
let fourthAsycnCall = try await API.fourthRequest(for: itemFour)

// Here we now have all the details we need to proceed while never blocking the `main` thread

Resources

Leave a comment