Is there a recommended approach for detecting WebSocket connectivity issues? More specifically, does URLSessionWebSocketTask have a way to access errors within CFNetwork?
My app maintains a WebSocket connection with a remote server, and I would like to notify the user that their connection has dropped when the phone loses network connectivity. I'm simulating a dropped network connection in my test environment by placing my phone in Airplane mode and deactivating WiFi. None of URLSessionWebSocketTask's delegates or callbacks pass back an error, and I only get the following log message:
Connection 1: encountered error(1:53) I'm using a URLSessionWebSocketDelegate and the urlSession(session:, webSocketTask:, didCloseWith:) does not get triggered, neither does webSocketTask.receive(completionHandler:)
I believe the log messages comes from CFNetwork since I can find the log within the Console app and the log references CFNetwork.
I found that webSocketTask.sendPing(pongReceiveHandler:) does eventually discover that connectivity is lost, but after a really long time. As far as I know, sendPing should probably run in a background task that runs every 30 seconds or so, and the error isn't discovered until about another 30+ seconds when the ping request times out. So, it could take 1+ minute(s) before the user is notified of the issue. I don't really like this approach since it requires extra code, extra network requests, and a very delayed response.
So, do errors within CFNetwork propagate to URLSessionWebSocketTask in any way? If not, I would really like if errors within CFNetwork propagated to webSocketTask.receive(completionHandler:) as a .warning URLSessionWebSocketTask.Message along with an error code. Ultimately, I would like to handle connection errors when they are encountered.
I noticed in another forum post that Apple changed iOS WebSockets in a beta release, so I tried to update my software without any luck. I updating macOS to 10.15.6 Beta (19G60d), iOS to 13.6 (17G5059c), and XCode to Version 12.0 beta 2 (12A6163b). However, XCode couldn't connect to my phone, and webSocketTask.send(message:) had intermittent string encoding issues.
System Details:
macOS 10.15.5 (1 June 2020 update)
iOS 13.5.1 (1 June 2020 update)
XCode Version 11.5 (11E608c)