PieSocket logo

Subscribe with iOS

Let's see how to connect easily to the PieSocket WebSocket API using Starscream on iOS.

Add Podfile

Add the following Podfile in your project

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

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://demo.websocket.me/v3/"+channelId+"?api_key="+apiKey+"&notifySelf")!)
request.timeoutInterval = 5
socket = WebSocket(request: request)
socket.delegate = self

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(_):
    case .pong(_):
    case .viabilityChanged(_):
    case .reconnectSuggested(_):
    case .cancelled:
        isConnected = false
    case .error(let error):
        isConnected = false

Publishing with Starscream

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

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

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

Happy coding!


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