<!--
{
  "availability" : [
    "iOS: 13.0.0 -",
    "iPadOS: 13.0.0 -",
    "macCatalyst: 13.1.0 -",
    "macOS: 10.15.0 -",
    "tvOS: 13.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 6.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Foundation",
  "identifier" : "/documentation/Foundation/URLSessionWebSocketTask/cancel(with:reason:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Foundation"
    ],
    "preciseIdentifier" : "c:objc(cs)NSURLSessionWebSocketTask(im)cancelWithCloseCode:reason:"
  },
  "title" : "cancel(with:reason:)"
}
-->

# cancel(with:reason:)

Sends a close frame with the given close code and optional close reason.

```
func cancel(with closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?)
```

## Parameters

`closeCode`

A [`URLSessionWebSocketTask.CloseCode`](/documentation/Foundation/URLSessionWebSocketTask/CloseCode-swift.enum) that indicates the reason for closing the connection.

`reason`

Optional further information to explain the closing. The value of this parameter is defined by the endpoints, not by the standard.

## Discussion

If you call [`cancel()`](/documentation/Foundation/URLSessionTask/cancel()) on the task instead of this method, it sends a cancellation frame with no close code or reason.

---

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)