PieSocket logo

Subscribe with iOS

Let's see how can we connect easily to a PieSocket channel using Starscream on iOS

Add Podfile

Add the following Podfile in your project

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'
use_frameworks!

pod 'Starscream', '~> 4.0.0'

Now install Starscream by running

pod install

Import the framework

import Starscream

Connect to PieSocket channel

Once you have imported the framework, use the following code to make the connection to our server

var apiKey = "oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm"; //Demo key, get yours at piesocket.com
var channelId = 1;

var request = URLRequest(url: URL(string: "wss://connect.websocket.in/v3/"+channelId+"?api_key="+apiKey+"&notifySelf")!)
request.timeoutInterval = 5
socket = WebSocket(request: request)
socket.delegate = self
socket.connect()

Handle channel events

Now you can listen to all events and implement it as per your business logic.

func didReceive(event: WebSocketEvent, client: WebSocket) {
    switch event {
    case .connected(let headers):
        isConnected = true
        print("PieSocket is connected: \(headers)")
    case .disconnected(let reason, let code):
        isConnected = false
        print("PieSocket is disconnected: \(reason) with code: \(code)")
    case .text(let string):
        print("Received text: \(string)")
    case .ping(_):
        break
    case .pong(_):
        break
    case .viabilityChanged(_):
        break
    case .reconnectSuggested(_):
        break
    case .cancelled:
        isConnected = false
    case .error(let error):
        isConnected = false
        handleError(error)
    }
}

Publishing with Starscream

If you have C2C enabled for your API key (You can manage C2C setting here), you can use this connection to publish messages.

{warning} We do not recommend this, you should use the REST API to publish messages.

socket.write(data: data) //write some Data over the socket!

Happy coding!

Help

Facing difficulties? Use the chat box on the bottom-right corner of this page to reach us.