iOS 13 URLSessionWebSocketTask tries to disconnect twice

2.4k views Asked by At

I am trying to implement web socket client with the new URLSession web socket support. Here is my simple implementation:

import Foundation

class WebSocketTest: NSObject {
    var session: URLSession?
    var task: URLSessionWebSocketTask?

    init(urlRequest: URLRequest) {
        super.init()
        self.session = URLSession(configuration: .default, delegate: self, delegateQueue: OperationQueue())
        self.task = self.session?.webSocketTask(with: urlRequest)
    }

    public func connect() {
        self.task?.resume()
    }

    public func disconnect() {
        self.task?.cancel(with: .goingAway, reason: nil)
    }
}

extension WebSocketTest: URLSessionWebSocketDelegate {
    func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocol: String?) {
        print("Connected!")
    }

    func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) {
        print("Disconnected!")
    }
}

This is my calling code:

let url = URL(string: "wss://echo.websocket.org")!
var request = URLRequest(url: url)
request.addValue("https://example.com", forHTTPHeaderField: "Origin")
self.webSocketTest = WebSocketTest(urlRequest: request)
self.webSocketTest?.connect()

DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
    self.webSocketTest?.disconnect()
}

And this is the output of execution:

Connected!
Disconnected!
Disconnected!
Connection 1: received failure notification

So, after canceling the task, the socket is trying to be disconnected twice. (I assume the last line of the output is there because it's trying to close already closed socket, otherwise it would be possible that just the delegate method is called twice)

Is it a bug in the framework or in my code? What am I doing wrong?

0

There are 0 answers