NSObject, URLSessionWebSocketDelegate { private var task: URLSessionWebSocketTask? func connect() { let session = URLSession(configuration: .default, delegate: self, delegateQueue: nil) task = session.webSocketTask(with: .init(string: "ws://example")!) doReceive() task?.resume() } func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocol: String?) { // connected } }