Skip to content
Daniel Rees edited this page Feb 12, 2018 · 14 revisions

Using SwiftPhoenixClient

Quick usage guidelines for the client

Creating a Socket

First, you need to create the socket that will join channels, receive events, and send messages

let socket = Socket(url: "ws://localhost:400/socket/websocket", params:["token": "Bearer 123", "user": "Full Name"])

This will create a Socket that is pointed to "ws://localhost:400/socket/websocket" with query parameters token and user appended to the URL. params is optional and can be left out if desired.

Channels and Events

Once your socket is created, you can join channel topics.

let socket = Socket(url: "ws://localhost:400/socket/websocket")
socket.join(topic: "rooms:lobby", payload: ["status":"joining"]) { (channel) in
    channel.on(event: "new:msg", handler: { (payload) in
        guard let username = payload["user"], let body = payload["body"] else { return }
    })
}

You can join as many channels as you need to by calling socket.join() again

Opening and Closing the Socket

Once a socket is initialized, you must call .open() before messages are received. You can open the socket before or after declaring which channels you would like to join. Messages are stored in a buffer while the socket is disconnected and then sent in order once the socket has established connection

let socket = Socket(url: "ws://localhost:400/socket/websocket")
socket.open()

When you're done, be sure to close the socket. .close(reset:) takes an optional parameter reset which, if true, will clean up channels. If you do not reset on close, opening the socket will rejoin all previous channels

socket.close()

Sending Messages

You can send message through the socket with any topic. Then you can receive events as the message sends

socket
    .send(event: "new:msg", topic: "room:lobby", payload: ["user": "Full Name", "body": "test message"])
    .receive("ok") { (payload) in
        // This will fire on an "ok" event
    }.receive("error", handler: { (payload) in
        // This will fire on an "error" event
    })
    .always {
        // This will fire on any event
    }

You can also send a message within a channel

channel.send(event: "new:msg", payload: ["user": "Full Name", "body": "test message"])
Clone this wiki locally