NWProtocolWebSocket: How to get the HTTP error?

I've managed to put together a WebSocket client in Swift using NWProtocolWebSocket (though the documentation does not make it easy.)

The point I'm stuck on is how to get a meaningful error if the server rejects the HTTP request, for example with a 404 or 403 status. The error reported to my stateUpdateHandler is a low-level POSIXErrorCode(rawValue: 53): Software caused connection abort).

Additionally, how can I add custom headers to the HTTP request, like authorization or cookies?

(I'm kind of wondering whether good ol' NSURLSession would have been a better choice -- TN3151 says: "Unless you have a specific reason to use URLSession, use Network framework for new WebSocket code", but at this point I feel that's bad advice.)

Answered by DTS Engineer in 886545022
how can I add custom headers to the HTTP request, like authorization or cookies?

You can set additional headers using nw_ws_options_add_additional_header (C) or the setAdditionalHeaders(_:) method (Swift).

how to get a meaningful error if the server rejects the HTTP request

This has come up before, without a great result. See this thread.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

how can I add custom headers to the HTTP request, like authorization or cookies?

You can set additional headers using nw_ws_options_add_additional_header (C) or the setAdditionalHeaders(_:) method (Swift).

how to get a meaningful error if the server rejects the HTTP request

This has come up before, without a great result. See this thread.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

NWProtocolWebSocket: How to get the HTTP error?
 
 
Q