Why does URLSession not call completion on the main thread?

When using URLSession in Swift for network tasks, you might notice that the completion handler is not called on the main thread by default. This behavior is important to understand as it affects how you update your user interface or handle data once a network request is complete.

The main reason for this is that URLSession operates asynchronously to ensure efficient network communications. To keep your app responsive, URLSession offloads network tasks to background threads. If the completion handler were to execute on the main thread, it could lead to UI freezes or other performance issues while waiting for a network response.

To update the UI after a network call, you need to explicitly switch to the main thread, which can be easily accomplished using DispatchQueue.main.async. Below is an example demonstrating how to handle this:

let url = URL(string: "https://api.example.com/data")! let task = URLSession.shared.dataTask(with: url) { data, response, error in if let error = error { print("Error: \(error)") return } if let data = data { // Process the data here DispatchQueue.main.async { // Update UI elements with the data } } } task.resume()

URLSession Swift Asynchronous Programming Completion Handler Main Thread Network Requests DispatchQueue