URLSessionWebSocketTask: Fatal error: Only one of message or error should be nil

981 views Asked by At

I've been getting this error randomly since I recently used URLSessionWebSocketTask, which causes my program to crash every time:

Fatal error: Only one of message or error should be nil

But I can't find a specific way to reproduce it, because I have no idea. It doesn't seem to be caused by network quality or any unsafe code I wrote.

So I'd like to ask, have you guys encountered this error recently? I need to know if it's caused by the SDK.

  • Xcode 11.3.1 (11C504)
  • macOS 10.15.3 (19D76)
  • iOS 13.3.1 (17D50)

p.s. I searched the internet and found only this related thread, and it didn't help.

1

There are 1 answers

0
Tony Wang On

After some digging, I've found a possible solution which can be found in this repo called websocket-apple, on GitHub: link

I also encountered this crash when I had the URLSession's delegateQueue set to .main. In the solution implemented by the websocket-apple repo, the wrapper around URLSessionWebSocket task creates a new OperationQueue and passes it in as the delegateQueue when initializing the URLSession.

This code block is where the delegateQueue to pass into the URLSession is created (copied directly from the linked repo)

private let webSocketQueue: DispatchQueue = DispatchQueue(label: "WebSocket.webSocketQueue")
private lazy var delegateQueue: OperationQueue = {
    let queue = OperationQueue()
    queue.name = "WebSocket.delegateQueue"
    queue.maxConcurrentOperationCount = 1
    queue.underlyingQueue = webSocketQueue
    return queue
}()

And line 77 has the initialization of the URLSession:

let session = URLSession(configuration: .default, delegate: delegate, delegateQueue: delegateQueue)