swift-request icon indicating copy to clipboard operation
swift-request copied to clipboard

Web Sockets

Open carson-katri opened this issue 4 years ago • 0 comments

Socket

Web socket support is a large task, so it may be a while. Here's an example of what the syntax could look like:

let ws = Socket {
    // Implicit "wss://"
    Url("echo.websocket.org")
    Header.Authorization(.basic(username: "username", password: "pass123"))
    ...
}
.onOpen { ... }
.onClose { reason in ... }
.onData { data in ... }
.onString { string in ... }
.onJson { json in ... }
.onError { err in ... }

ws.send("Hello world")
ws.send(myData)
// Sometime later
ws.close()

onClose would return a SocketCloseEvent, which contains the code (URLSessionWebSocketTask.CloseCode) and the reason. You could pass this into the .close method:

ws.close(SocketCloseEvent(code: .goingAway, reason: "I had a problem!"))
ws.close(code: .goingAway, reason: nil)

This will be built atop URLSessionWebSocketTask, available in iOS 13. Custom frames will not be supported with this implementation.

AnySocket

A Socket with Codable support. It could be used with the onObject callback:

struct Message: Decodable {
    let sender: String
    let body: String
}
AnySocket<Message> {
    Url("messaging.example.com")
}
.onObject { message in ... }

SocketView

SwiftUI compatibility is key. It could look something like this:

var body: some View {
    SocketView(Message.self, Socket { ... }) { messages in
        List(messages) { message in
            Text(message.sender)
                .font(.caption)
            Text(message.body)
        }
    }
}

It gives you an array of the response type. The example above shows Codable support.

carson-katri avatar Aug 03 '19 17:08 carson-katri