<!--
{
  "availability" : [
    "iOS: 7.0.0 -",
    "iPadOS: 7.0.0 -",
    "macCatalyst: 13.1.0 -",
    "macOS: 10.9.0 -",
    "tvOS: 9.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 2.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Foundation",
  "identifier" : "/documentation/Foundation/URLSessionTask/cancel()",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Foundation"
    ],
    "preciseIdentifier" : "c:objc(cs)NSURLSessionTask(im)cancel"
  },
  "title" : "cancel()"
}
-->

# cancel()

Cancels the task.

```
func cancel()
```

## Discussion

This method returns immediately, marking the task as being canceled. Once a task is marked as being canceled, [`urlSession(_:task:didCompleteWithError:)`](/documentation/Foundation/URLSessionTaskDelegate/urlSession(_:task:didCompleteWithError:)) will be sent to the task delegate, passing an error in the domain [`NSURLErrorDomain`](/documentation/Foundation/NSURLErrorDomain) with the code [`NSURLErrorCancelled`](/documentation/Foundation/NSURLErrorCancelled-swift.var). A task may, under some circumstances, send messages to its delegate before the cancelation is acknowledged.

This method may be called on a task that is suspended.

## See Also

[`cancel(byProducingResumeData:)`](/documentation/Foundation/URLSessionDownloadTask/cancel(byProducingResumeData:))

Cancels a download and calls a callback with resume data for later use.



---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)