carson-katri / carson-katri/swift-request
Web Sockets
- Dominant language
- Swift
- Stars
- 740
- Forks
- 42
- PR merge metrics
- No merged PRs in 30d
Description
## `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:
```swift
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:
```swift
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:
```swift
struct Message: Decodable {
let sender: String
let body: String
}
AnySocket {
Url("messaging.example.com")
}
.onObject { message in ... }
```
## `SocketView`
SwiftUI compatibility is key. It could look something like this:
```swift
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.
Contributor guide
Assessment
This issue has not been assessed yet.