Contents

URLSessionWebSocketTask

A URL session task that communicates over the WebSockets protocol standard.

Declaration

class URLSessionWebSocketTask

Overview

URLSessionWebSocketTask is a concrete subclass of URLSessionTask that provides a message-oriented transport protocol over TCP and TLS in the form of WebSocket framing. It follows the WebSocket Protocol defined in RFC 6455.

You create a URLSessionWebSocketTask with either a ws: or wss: URL. When creating the task, you can also provide a list of protocols to advertise during the handshake phase. Once the handshake completes, your app receives notifications through the session’s delegate.

You send data with send(_:completionHandler:) and receive data with receive(completionHandler:). The task performs reads and writes asynchronously, and allows you to send and receive messages that contain both binary frames and UTF-8 encoded text frames. The task enqueues any reads or writes you perform prior to the handshake’s completion, and executes them after the handshake completes.

URLSessionWebSocketTask supports redirection and authentication like other types of tasks do, using the methods in URLSessionTaskDelegate. The WebSocket task calls the redirection and authentication delegate methods prior to completing the handshake. The WebSocket task also supports cookies, by storing cookies to the session configuration’s httpCookieStorage, and attaches cookies to outgoing HTTP handshake requests.

Topics

Sending and receiving data

Sending ping frames

Closing the connection

Instance Methods

See Also

Adding WebSocket tasks to a session