How to cancel urlsession

Asked on 08/04/2024

1 search

To cancel a URLSession in Swift, you can call the cancel() method on the URLSessionTask instance that you want to cancel. Here is a basic example:

let task = URLSession.shared.dataTask(with: url) { data, response, error in
    // Handle response here
}

// Start the task
task.resume()

// Cancel the task
task.cancel()

In this example, task is an instance of URLSessionTask. By calling task.cancel(), you can cancel the ongoing network request.

For more information on concurrency and task management in Swift, you might find the session A Swift Tour: Explore Swift’s features and design particularly useful, especially the section on concurrency.