//MARK: IB Outlets
var ws: WSS = .init(stringURL: "ws://53b6-2405-201-5009-610f-24fa-6b65-905b-b188.ngrok.io/cable")
var clientOptions: ACClientOptions = .init(debug: true, reconnect: true)
var client: ACClient!
var channelOptions: ACChannelOptions!
var channel: ACChannel!
override func viewDidLoad() {
super.viewDidLoad()
self.setupActionCable()
}
func setupActionCable() {
/// web socket client
//self.ws = .init(stringURL: "ws://localhost:3001/cable")
/// action cable client
//self.clientOptions = .init(debug: false, reconnect: true)
self.client = .init(ws: ws, options: clientOptions)
/// on server you can get this with env['HTTP_COOKIE']
client.headers = ["Authorization": appUser.auth_token!]
/// make channel
/// buffering - buffering messages if disconnect and flush after reconnect
let channelOptions: ACChannelOptions = .init(buffering: true, autoSubscribe: false)
/// params to subscribe passed inside the identifier dictionary
let identifier: [String: Any] = ["conversation_id": "2"]
channel = (client.makeChannel(name: "ConversationChannel", 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? self.channel.subscribe()
}
}