Support Action Cable Swift development by giving a ⭐️
Action Cable Swift
Action Cable Swift is a client library being released for Action Cable Rails 5 which makes it easy to add real-time features to your app. This Swift client inspired by “Swift-ActionCableClient”, but it not support now and I created Action-Cable-Swift.
Also web sockets client are now separate from the client.
I highly recommend not using Starscream to implement a WebSocket, because they have a strange implementation that does not allow conveniently reconnecting to a remote server after disconnecting. There is also a cool and fast alternative from the Swift Server Work Group (SSWG), package named Websocket-kit.
SPOILER: If you still want to use "Starscream", then you can to copy this code for websocket client
import Foundation
import Starscream
class WSS: ACWebSocketProtocol, WebSocketDelegate {
var url: URL
var ws: WebSocket
init(stringURL: String) {
url = URL(string: stringURL)!
ws = WebSocket(request: URLRequest(url: url))
ws.delegate = self
}
var onConnected: ((_ headers: [String : String]?) -> Void)?
var onDisconnected: ((_ reason: String?) -> Void)?
var onCancelled: (() -> Void)?
var onText: ((_ text: String) -> Void)?
var onBinary: ((_ data: Data) -> Void)?
var onPing: (() -> Void)?
var onPong: (() -> Void)?
func connect(headers: [String : String]?) {
ws.request.allHTTPHeaderFields = headers
ws.connect()
}
func disconnect() {
ws.disconnect()
}
func send(data: Data) {
ws.write(data: data)
}
func send(data: Data, _ completion: (() -> Void)?) {
ws.write(data: data, completion: completion)
}
func send(text: String) {
ws.write(string: text)
}
func send(text: String, _ completion: (() -> Void)?) {
ws.write(string: text, completion: completion)
}
func didReceive(event: WebSocketEvent, client: WebSocket) {
switch event {
case .connected(let headers):
onConnected?(headers)
case .disconnected(let reason, let code):
onDisconnected?(reason)
case .text(let string):
onText?(string)
case .binary(let data):
onBinary?(data)
case .ping(_):
onPing?()
case .pong(_):
onPong?()
case .cancelled:
onCancelled?()
default: break
}
}
}
Next step to use ActionCableSwift
import ActionCableSwift
/// web socket client
let ws: WSS = .init(stringURL: "ws://localhost:3001/cable")
/// action cable client
let clientOptions: ACClientOptions = .init(debug: false, reconnect: true)
let client: ACClient = .init(ws: ws, options: clientOptions)
/// pass headers to connect
/// on server you can get this with env['HTTP_COOKIE']
client.headers = ["COOKIE": "Value"]
/// make channel
/// buffering - buffering messages if disconnect and flush after reconnect
let channelOptions: ACChannelOptions = .init(buffering: true, autoSubscribe: true)
/// params to subscribe passed inside the identifier dictionary
let identifier: [String: Any] = ["key": "value"]
let channel: ACChannel = client.makeChannel(name: "RoomChannel", identifier: identifier, options: channelOptions)
// !!! Make sure that the client and channel objects is declared "globally" and lives while your socket connection is needed
channel.addOnSubscribe { (channel, optionalMessage) in
print(optionalMessage)
}
channel.addOnMessage { (channel, optionalMessage) in
print(optionalMessage)
}
channel.addOnPing { (channel, optionalMessage) in
print("ping")
}
/// Connect
client.connect()
Manual Subscribe to a Channel
client.addOnConnected { (headers) in
try? channel.subscribe()
}
Support Action Cable Swift development by giving a ⭐️
Action Cable Swift
Action Cable Swift is a client library being released for Action Cable Rails 5 which makes it easy to add real-time features to your app. This Swift client inspired by “Swift-ActionCableClient”, but it not support now and I created Action-Cable-Swift.
Also web sockets client are now separate from the client.
Installation
To install, simply:
Swift Package Manager
Add the following line to your
Package.swift
Cocoa Pods
Add the following line to your
Podfile
and you can import ActionCableSwift
Usage
Your WebSocketService should to implement the
ACWebSocketProtocol
protocol.Use with Websocket-kit
I highly recommend not using Starscream to implement a WebSocket, because they have a strange implementation that does not allow conveniently reconnecting to a remote server after disconnecting. There is also a cool and fast alternative from the Swift Server Work Group (SSWG), package named Websocket-kit.
Websocket-kit is SPM(Swift Package Manager) client library built on Swift-NIO
Package.swift
or inside xcode
SPOILER: Recommended implementation WSS based on Websocket-kit(Swift-NIO)
This is propertyWrapper for threadsafe access to webSocket instance
This is implementation WSS
Use with Starscream
SPOILER: If you still want to use "Starscream", then you can to copy this code for websocket client
Next step to use ActionCableSwift
Manual Subscribe to a Channel
Channel Callbacks
Perform an Action on a Channel
Authorization & Headers
Requirements
Any Web Socket Library, e.g.
Websocket-kit
Starscream
Author
Me
License
ActionCableSwift is available under the MIT license. See the LICENSE file for more info.