WebSocketKit is a small wrapper around the `Network` framework to work with websocket connections
To integrate using Apple's Swift Package Manager, add the following as a dependency to your Package.swift
:
dependencies: [
.package(url: "https://github.com/alexanderwe/WebSocketKit.git", from: "1.0.0")
]
Alternatively navigate to your Xcode project, select Swift Packages
and click the +
icon to search for WebSocketKit
.
If you prefer not to use any of the aforementioned dependency managers, you can integrate WebSocketKit
into your project manually. Simply drag the Sources
Folder into your Xcode project.
At first import WebSocketKit
import WebSocketKit
Define a WebsSocket
instance
let websocket = WebsSocket(url: URL(string: "wss://echo.websocket.org")!)
It also makes sense to create a instance of a class that conforms to the WebSocketConnectionDelegate
in order to receive websocket events. Be aware that you also need to import the Network
framework in order to have access to NWProtocolWebSocket
.
import Network
class WebSocketDelegate: WebSocketConnectionDelegate {
func webSocketDidConnect(connection: WebSocketConnection) {
print("WebSocket did connect")
}
func websocketDidPrepare(connection: WebSocketConnection) {
print("WebSocket did prepare")
}
func webSocketDidDisconnect(connection: WebSocketConnection, closeCode: NWProtocolWebSocket.CloseCode, reason: Data?) {
print("WebSocket did disconnect")
}
func websocketDidCancel(connection: WebSocketConnection) {
print("WebSocket did cancel")
}
func webSocketDidReceiveError(connection: WebSocketConnection, error: Error) {
print("WebSocket did receive error: \(error)")
}
func webSocketDidReceivePong(connection: WebSocketConnection) {
print("WebSocket did receive pong")
}
func webSocketDidReceiveMessage(connection: WebSocketConnection, string: String) {
print("WebSocket did receive string message: \(string)")
}
func webSocketDidReceiveMessage(connection: WebSocketConnection, data: Data) {
print("WebSocket did receive data message")
}
}
Set an instance of the delegate instance to the Websocket
instance and start listening for events
let delegate = WebSocketDelegate()
websocket.delegate = delegate
websocket.connect() // Connects to the url specified in the initializer and listens for messages
Often it is necessary to attach custom headers to the connection. You can do so by specifying them in the initializer of the Websocket
class.
let websocket = Websocket(url: URL(string: "wss://echo.websocket.org")!,
additionalHeaders: [
"Authorization:": "Bearer <someToken>",
"My-Custom-Header-Key:": "My-Custom-Header-Value"
]
)
Contributions are very welcome 🙌