PhoenixWebSocket is a websockets framework designed to work with Phoenix Framework. It uses Starscream under the hood.
github "almassapargali/PhoenixWebSocket"
Don't forget to append /websocket, to specify transport, to you socket path.
let url = NSURL(string: "ws://localhost:4000/socket/websocket")!
// create socket and channel
socket = Socket(url: url)
channel = Channel(topic: "rooms:lobby")
// you can optionally set join payload
channel.joinPayload = ["user_id": 123]
socket.join(channel)
// you can optionally enable logging
socket.enableLogging = true
// then connect
socket.connect()This framework users NSTimers extensively for reconnecting or sending heartbeat message. And since iOS invalidates all NSTimers when app goes background, it's recommended to call connect again on UIApplicationWillEnterForegroundNotification. Like:
override func viewDidLoad() {
super.viewDidLoad()
subscription = NSNotificationCenter.defaultCenter().addObserverForName(
UIApplicationWillEnterForegroundNotification, object: nil, queue: nil) { [weak self] _ in
self?.socket.connect()
}
}
deinit {
if let observer = subscription {
NSNotificationCenter.defaultCenter().removeObserver(observer)
}
}And, also, since NSTimers retains their targets, it's hardly recommended to call disconnect on deinit. Disconnecting would invalidate all timers:
deinit {
socket.disconnect(0)
}When creating socket:
let params = ["token": "abc...", ...]
socket = Socket(url: url, params: params)And in server:
def connect(%{"token" => token}, socket) do
..
endchannel
// channel connection status
.onStatusChange { newStatus in ... }
.on("new:msg") { message in print(message.payload) }
.on("user:joined") { message in ... }You can optionally pass message callback if server replies to this message.
let payload = ["user": "Chuck Norris", "body": "Two seconds till"]
socket.send(channel, event: "new:msg", payload: payload) { res in
switch res {
case .Success(let response): // received server response
switch response { // server replied on handle_in with {:reply, response, socket}
case .Ok(let payload): // response is {:ok, payload}
case let .Error(reason, payload): // response is {:error, %{reason: "Good reason"}}
}
case .Error(let error): // connection error
}
}To run demo app:
- Clone chrismccord/phoenix_chat_example and run it locally.
- Clone this repo, then
initandupdatesubmodules. - Open
PhoenixChatDemo/PhoenixChatDemo.xcodeprojand run it.
PhoenixWebSocket is available under the MIT license. See the LICENSE file for more info.