Skip to content

Instantly share code, notes, and snippets.

@ecpplus
Created October 14, 2016 13:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ecpplus/e5a97b28f89faf39d2f5400527015d1a to your computer and use it in GitHub Desktop.
Save ecpplus/e5a97b28f89faf39d2f5400527015d1a to your computer and use it in GitHub Desktop.
Connect to PhoenixFramework WebSocket from Swift.
import UIKit
import Starscream
class ViewController: UIViewController, WebSocketDelegate {
var socket = WebSocket(url: URL(string: "ws://10.0.1.2:4000/socket/websocket")!, protocols: [])
override func viewDidLoad() {
super.viewDidLoad()
socket.delegate = self
socket.connect()
}
var ref: Int = 0
// MARK: Websocket Delegate Methods.
func websocketDidConnect(socket: WebSocket) {
print("websocket is connected")
ref += 1
let dict = [
"ref" : String(ref),
"topic": "room:ebe99a2c-cccb-4409-8bdd-d1d3b7fa2eb0",
"event": "phx_join",
"payload": ["name": "chu"]
] as [String : Any]
let jsonData = try! JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
socket.write(data: jsonData)
}
func websocketDidDisconnect(socket: WebSocket, error: NSError?) {
if let e = error {
print("websocket is disconnected: \(e.localizedDescription)")
} else {
print("websocket disconnected")
}
}
func websocketDidReceiveMessage(socket: WebSocket, text: String) {
print("Received text: \(text)")
}
func websocketDidReceiveData(socket: WebSocket, data: Data) {
print("Received data: \(data.count)")
}
func sendText() {
ref += 1
let dict = [
"ref" : String(ref),
"topic": "room:ebe99a2c-cccb-4409-8bdd-d1d3b7fa2eb0",
"event": "new_msg",
"payload": ["body": "hello"]
] as [String : Any]
let jsonData = try! JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
socket.write(data: jsonData)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment