Synchronous v/s Asynchronous API call in Swift
In Swift, the main difference between a synchronous API call and an asynchronous one is how you handle the response data.
Synchronous call
With a synchronous API call, the app freezes while the call is being made. The app remain unresponsive until a response is available.
Here is an example using the URLSession
:
let url = URL(string: "https://www.boredapi.com/api/activity")!
let request = URLRequest(url: url)
do {
let data = try URLSession.shared.data(request: request)
let activity = try JSONDecoder().decode(Activity.self, from: data)
self.activities = activity
} catch {
print("Error decoding data")
}
Asynchronous call
With an asynchronous API call, the app remain responsive while the API call is being made.
Here is an example using the URLSession
:
let url = URL(string: "https://www.boredapi.com/api/activity")!
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print("Error fetching data: \(error)")
return
}
guard let data = data else {
print("No data")
return
}
do {
let activity = try JSONDecoder().decode(Activity.self, from: data)
DispatchQueue.main.async {
self.activities = activity
}
} catch {
print("Error decoding data: \(error)")
}
}.resume()
As can be noted, the asynchronous API call uses a closure that gets called when the response comes back. This closure allows you to handle the response data without blocking the main thread of your app.