Support Action Cable Swift development by giving a ⭐️
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.
To install, simply:
Add the following line to your Package.swift
// ...
.package(name: "ActionCableSwift", url: "https://github.com/nerzh/Action-Cable-Swift.git", from: "1.0.0"),
targets: [
.target(
name: "YourPackageName",
dependencies: [
.product(name: "ActionCableSwift", package: "ActionCableSwift")
])
// ...
import ActionCableSwift
/// action cable client
let clientOptions: ACClientOptions = .init(debug: false, reconnect: true)
let client: ACClient = .init(stringURL: "ws://localhost:3001/cable", 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()
client.addOnConnected { (headers) in
try? channel.subscribe()
}
func addOnMessage(_ handler: @escaping (_ channel: ACChannel, _ message: ACMessage?) -> Void)
func addOnSubscribe(_ handler: @escaping (_ channel: ACChannel, _ message: ACMessage?) -> Void)
func addOnUnsubscribe(_ handler: @escaping (_ channel: ACChannel, _ message: ACMessage?) -> Void)
func addOnRejectSubscription(_ handler: @escaping (_ channel: ACChannel, _ message: ACMessage?) -> Void)
func addOnPing(_ handler: @escaping (_ channel: ACChannel, _ message: ACMessage?) -> Void)
// Send an action
channel.addOnSubscribe { (channel, optionalMessage) in
try? channel.sendMessage(actionName: "speak", params: ["test": 10101010101])
}
client.headers = [
"Authorization": "sometoken"
]
ACWebSocketProtocol
protocol and use another initializator for ACClientimport ActionCableSwift
/// web socket client
let ws: YourWSS = .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)
Me
ActionCableSwift is available under the MIT license. See the LICENSE file for more info.