Junior
What is the difference between synchronous and asynchronous requests?
sobes.tech AI
Answer from AI
Synchronous requests block the current thread until a response is received. Asynchronous requests do not block the thread; the response is handled upon completion of the operation, usually through a callback mechanism, delegate, or closure.
| Characteristic | Synchronous request | Asynchronous request |
|---|---|---|
| Thread blocking | Yes | No |
| UI responsiveness | Can block the UI | Does not block the UI |
| Implementation complexity | Simpler | More complex (state management) |
| Usage in iOS | Rarely, only for short tasks, not on the main thread | Preferably, especially for long operations |
Example of an asynchronous request using URLSession:
// Create a URLSessionTask
let task = URLSession.shared.dataTask(with: url) { data, response, error in
// This block executes asynchronously after the request completes
if let error = error {
print("Error: \(error.localizedDescription)")
return
}
// Handling received data
if let data = data {
print("Data received, bytes: \(data.count)")
}
// UI updates should happen on the main thread
DispatchQueue.main.async {
// Update UI
}
}
// Start the task
task.resume()
// Code here executes immediately, without waiting for the request to finish
print("Request sent")