URLSession and Swift Concurrency: Does cancelling a Task abort the underlying dataTask?
23.5K reputation · 18 Dec 2021, 10:07 UTC
Goal
When a Swift Task is cancelled, ensure that the associated URLSessionDataTask is terminated immediately to prevent unnecessary network usage and battery drain.
Challenge
URLSession’s data(for:) overload forwards cancellation only when explicitly used; otherwise cancelling the enclosing Task does not affect the underlying network task. Similarly, Combine’s .timeout operator emits a timeout error but does not cancel the upstream URLSessionDataTask. The documented behavior of Swift 6 structured concurrency regarding automatic propagation of cancellation to URLSession is not clearly specified, leaving developers to guess whether additional manual cancellation is required.
Questions
- Does cancelling a Swift Task that awaits
URLSession.shared.data(for:)automatically cancel the underlyingURLSessionDataTaskwhen using the overload that forwards cancellation? - What is the documented behavior of Combine’s
.timeoutwhen applied to aURLSessiondataTaskPublisherwith respect to the upstream network task? - Is there a single, documented pattern that guarantees a timeout or cancellation always aborts the network request across URLSession, Combine, and Swift concurrency?