Swift framework for working with websockets on Phoenix
Swift Objective-C Ruby
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
Carthage/Checkouts update lib for Swift 3 Sep 21, 2016
PhoenixChatDemo update demo for Swift 3 Sep 21, 2016
PhoenixWebSocket.xcodeproj
PhoenixWebSocket Allow to put Any into JSON Jan 12, 2017
.gitignore added Starscream as submodule Mar 18, 2016
.gitmodules added Demo project with deps Mar 18, 2016
.swift-version Add podspec Oct 21, 2016
Cartfile
Cartfile.resolved update lib for Swift 3 Sep 21, 2016
LICENSE added LICENSE Mar 19, 2016
PhoenixWebSocket.podspec matching tag name Jan 10, 2017
README.md added readme Mar 19, 2016

README.md

PhoenixWebSocket

PhoenixWebSocket is a websockets framework designed to work with Phoenix Framework. It uses Starscream under the hood.

Installation

Carthage

github "almassapargali/PhoenixWebSocket"

Usage

Connecting

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)
}

Token authentication

When creating socket:

let params = ["token": "abc...", ...]
socket = Socket(url: url, params: params)

And in server:

def connect(%{"token" => token}, socket) do
  ..
end

Receiving messages

channel
  // channel connection status
  .onStatusChange { newStatus in ... }
  .on("new:msg") { message in print(message.payload) }
  .on("user:joined") { message in ... }

Sending messages

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
  }
}

See demo app

To run demo app:

  1. Clone chrismccord/phoenix_chat_example and run it locally.
  2. Clone this repo, then init and update submodules.
  3. Open PhoenixChatDemo/PhoenixChatDemo.xcodeproj and run it.

License

PhoenixWebSocket is available under the MIT license. See the LICENSE file for more info.