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.

Enhance your UI animations and transitions
Explore how to adopt the zoom transition in navigation and presentations to increase the sense of continuity in your app, and learn how to animate UIKit views with SwiftUI animations to make it easier to build animations that feel continuous.

What’s new in location authorization
Location authorization is turning 2.0. Learn about new recommendations and techniques to get the authorization you need, and a new system of diagnostics that can let you know when an authorization goal can’t be met.

Go further with Swift Testing
Learn how to write a sweet set of (test) suites using Swift Testing’s baked-in features. Discover how to take the building blocks further and use them to help expand tests to cover more scenarios, organize your tests across different suites, and optimize your tests to run in parallel.