URLSessionWebSocketTask.receive() doesn't throw on cancel()

634 views Asked by At

I am repeatedly calling URLSessionWebSocketTask.receive. I've tried recursively calling the version with the completion handler, as well as looping over the new async version.

At some point, I'm not receiving any more messages, and I want to cancel the web socket. So I call URLSessionWebSocketTask.cancel(). In the log, I see the message [websocket] Read completed with an error Operation canceled. But the completion handler is never called/the async receive method never returns. This means that the Task I launched to do the receiving never closes.

Why doesn't the completion handler get called when the web socket is cancelled?

1

There are 1 answers

0
Jimmie On

Are you actually seeing a leak with the closure-based approach?

I see a leak when using the async version, but if I use the closure-version the URLSessionWebSocketTask-object is freed. I don't get any call to the closure, but for my use case that does not matter.

If I use the delegate on the session I will get a callback when the websocket is closed, but I have to call session.invalidateAndCancel when cleaning up.

I also needed to add [weak self] to the closure since I call my receive-function recursively, capturing self.