Created
October 14, 2016 13:14
-
-
Save ecpplus/e5a97b28f89faf39d2f5400527015d1a to your computer and use it in GitHub Desktop.
Connect to PhoenixFramework WebSocket from Swift.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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