ios – URLSessionWebSocket Not Calling didClose Delegate Technique


I am attempting to make use of URLSessionWebSocket to ascertain an online socket connection. I’ve the next code to make that occur:

class WebSocketManager: NSObject, URLSessionTaskDelegate, URLSessionWebSocketDelegate {
    non-public var urlSession: URLSession!
    var webSocketTask: URLSessionWebSocketTask?

    func run() {
        urlSession = URLSession(configuration: .default, delegate: self, delegateQueue: nil)
        let url = URL(string: "ws://")!
        let urlRequest = URLRequest(url: url)
        webSocketTask = urlSession.webSocketTask(with: urlRequest)

    func ship() {
        webSocketTask!.ship(URLSessionWebSocketTask.Message.string("Howdy from Consumer"), completionHandler: { error in
            if let error = error {
                print("Error sending message: (error)")
            } else {
                print("Despatched message")

    func obtain() {
        webSocketTask?.obtain(completionHandler: { end in
            swap end result {
            case .failure(let error):
                print("Error receiving message: (error)")
            case .success(let message):
                swap message {
                case .string(let textual content):
                    print("Obtained: (textual content)")
                case .knowledge(let knowledge):
                    print("Obtained binary message: (knowledge)")
                @unknown default:

    func urlSession(_ session: URLSession, process: URLSessionTask, didCompleteWithError error: Error?) {

    func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {

    func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, purpose: Information?) {
        print("Did shut with")

    func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocol: String?) {

Then I am utilizing wscat --listen 3000 --slash in my command line to check an online socket server to check with.

Once I run the appliance, I can ship messages, and obtain messages after calling the related strategies. That every one works high-quality.

Nonetheless, once I hit Command + C to exit the online server, it by no means lets the consumer utility know. The delegate strategies do not get known as when that happens. So the consumer has no approach of figuring out when the connection has been terminated.

How can I repair this and get alerted when the online socket is disconnected?


Leave a Reply