Sobes.tech
Junior

Does the data task method execute synchronously or asynchronously?

sobes.tech AI

Answer from AI

Asynchronously.

// URLSessionDataTask executes asynchronously.
// It returns control immediately,
// and the result (data, response, error) is passed to the completion handler
// after the network request completes in a background thread.
let task = URLSession.shared.dataTask(with: url) { data, response, error in
    // This block of code executes asynchronously
    // after receiving a response from the server or encountering an error.
    if let data = data {
        print("Received data: \(data.count) bytes")
    } else if let error = error {
        print("Error: \(error.localizedDescription)")
    }
}

// Start the task.
// The resume() method simply queues the task.
task.resume()

// Code after task.resume() executes immediately,
// without waiting for the network request to complete.
print("Task started...")
Does the data task method execute synchronously or… - sobes.tech