• Stars
    star
    267
  • Rank 148,046 (Top 4 %)
  • Language
    Swift
  • License
    MIT License
  • Created about 9 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Pusher Channels websocket library for Swift

Pusher Channels Swift Client (also works with Objective-C)

Build Status codecov Latest Release CocoaPods API Docs Supported Platforms Swift Versions Twitter GitHub license

This is the Pusher Channels websocket client, PusherSwift, which supports iOS, macOS (OS X) and tvOS. It works with Swift and Objective-C.

For tutorials and more in-depth information about Pusher Channels, visit our official docs.

Supported platforms

  • Swift 5.0 and above
  • Xcode 12.0 and above
  • Can be used with Objective-C

Deployment targets

  • iOS 13.0 and above
  • macOS (OS X) 10.15 and above
  • tvOS 13.0 and above

Legacy OS support

If you need support for older versions of iOS, macOS or tvOS, please use the latest v8.x release of the SDK.

I just want to copy and paste some code to get me started

What else would you want? Head over to one of our example apps:

Table of Contents

Installation

CocoaPods

CocoaPods is a dependency manager for Cocoa projects and is our recommended method of installing PusherSwift and its dependencies.

If you don't already have the Cocoapods gem installed, run the following command:

$ gem install cocoapods

To integrate PusherSwift into your Xcode project using CocoaPods, specify it in your Podfile:

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

pod 'PusherSwift', '~> 10.1.0'

Then, run the following command:

$ pod install

If you find that you're not having the most recent version installed when you run pod install then try running:

$ pod cache clean
$ pod repo update PusherSwift
$ pod install

Also you'll need to make sure that you've not got the version of PusherSwift locked to an old version in your Podfile.lock file.

Carthage

Carthage is a decentralized dependency manager that automates the process of adding frameworks to your Cocoa application.

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate PusherSwift into your Xcode project using Carthage, specify it in your Cartfile:

github "pusher/pusher-websocket-swift"

Carthage will produce a number of frameworks. You need to include the following framework binaries in your project from the Carthage/Build directory: PusherSwift, NWWebSocket and TweetNacl

Xcode 12 considerations

There have been changes to the architectures included when building universal frameworks under Xcode 12.0 and above. This is to support the introduction of the Apple Silicon family of processors.

It is strongly recommended that you integrate PusherSwift using the --use-xcframeworks flag, running Carthage 0.37.0 or above. There are full instructions for this (as well as instructions for migrating to XCFrameworks if you are already integrating using Carthage).

Alternatively, if you are building using an Intel Mac and do not want to migrate to build Carthage dependencies using XCFrameworks there is a workaround to build successfully. You can find an example of this workaround, which is used for running the 'Consumption-Tests' here.

Swift Package Manager

To integrate PusherSwift into your project using Swift Package Manager, you can add the library as a dependency in Xcode โ€“ see the docs. The package repository URL is:

https://github.com/pusher/pusher-websocket-swift.git

Alternatively, you can add PusherSwift as a dependency in your Package.swift file. For example:

// swift-tools-version:5.1
import PackageDescription

let package = Package(
    name: "YourPackage",
    products: [
        .library(
            name: "YourPackage",
            targets: ["YourPackage"]),
    ],
    dependencies: [
        .package(url: "https://github.com/pusher/pusher-websocket-swift.git", from: "10.1.0"),
    ],
    targets: [
        .target(
            name: "YourPackage",
            dependencies: ["PusherSwift"]),
    ]
)

You will then need to include an import PusherSwift statement in any source files where you wish to use the SDK.

Configuration

There are a number of configuration parameters which can be set for the Pusher client. For Swift usage they are:

  • authMethod (AuthMethod) - the method you would like the client to use to authenticate subscription requests to channels requiring authentication (see below for more details)
  • useTLS (Bool) - whether or not you'd like to use TLS encrypted transport or not, default is true
  • autoReconnect (Bool) - set whether or not you'd like the library to try and automatically reconnect upon disconnection (where possible). See Reconnection for more info
  • host (PusherHost) - set a custom value for the host you'd like to connect to, e.g. PusherHost.host("ws-test.pusher.com")
  • port (Int) - set a custom value for the port that you'd like to connect to
  • activityTimeout (TimeInterval) - after this time (in seconds) without any messages received from the server, a ping message will be sent to check if the connection is still working; the default value is supplied by the server, low values will result in unnecessary traffic.
View legacy configuration options
  • attemptToReturnJSONObject (Bool) - whether or not you'd like the library to try and parse your data as JSON (or not, and just return a string)

The authMethod parameter must be of the type AuthMethod. This is an enum defined as:

public enum AuthMethod {
    case endpoint(authEndpoint: String)
    case authRequestBuilder(authRequestBuilder: AuthRequestBuilderProtocol)
    case inline(secret: String)
    case authorizer(authorizer: Authorizer)
    case noMethod
}
  • endpoint(authEndpoint: String) - the client will make a POST request to the endpoint you specify with the socket ID of the client and the channel name attempting to be subscribed to
  • authRequestBuilder(authRequestBuilder: AuthRequestBuilderProtocol) - you specify an object that conforms to the AuthRequestBuilderProtocol (defined below), which must generate an URLRequest object that will be used to make the auth request
  • inline(secret: String) - your app's secret so that authentication requests do not need to be made to your authentication endpoint and instead subscriptions can be authenticated directly inside the library (this is mainly designed to be used for development)
  • authorizer(authorizer: Authorizer) - you specify an object that conforms to the Authorizer protocol which must be able to provide the appropriate auth information
  • noMethod - if you are only using public channels then you do not need to set an authMethod (this is the default value)

This is the AuthRequestBuilderProtocol definition:

public protocol AuthRequestBuilderProtocol {
    func requestFor(socketID: String, channelName: String) -> URLRequest?
}

This is the Authorizer protocol definition:

public protocol Authorizer {
    func fetchAuthValue(socketID: String, channelName: String, completionHandler: (PusherAuth?) -> ())
}

where PusherAuth is defined as:

public class PusherAuth: NSObject {
    public let auth: String
    public let channelData: String?
    public let sharedSecret: String?

    public init(auth: String, channelData: String? = nil, sharedSecret: String? = nil) {
        self.auth = auth
        self.channelData = channelData
        self.sharedSecret = sharedSecret
    }
}

Provided the authorization process succeeds you need to then call the supplied completionHandler with a PusherAuth object so that the subscription process can complete.

If for whatever reason your authorization process fails then you just need to call the completionHandler with nil as the only parameter.

Note that if you want to specify the cluster to which you want to connect then you use the host property as follows:

Swift

let options = PusherClientOptions(
    host: .cluster("eu")
)

Objective-C

OCAuthMethod *authMethod = [[OCAuthMethod alloc] initWithAuthEndpoint:@"https://your.authendpoint/pusher/auth"];
OCPusherHost *host = [[OCPusherHost alloc] initWithCluster:@"eu"];
PusherClientOptions *options = [[PusherClientOptions alloc]
                                initWithOcAuthMethod:authMethod
                                autoReconnect:YES
                                ocHost:host
                                port:nil
                                useTLS:YES
                                activityTimeout:nil];

All of these configuration options need to be passed to a PusherClientOptions object, which in turn needs to be passed to the Pusher object, when instantiating it, for example:

Swift

let options = PusherClientOptions(
    authMethod: .endpoint(authEndpoint: "http://localhost:9292/pusher/auth")
)

let pusher = Pusher(key: "APP_KEY", options: options)

Objective-C

OCAuthMethod *authMethod = [[OCAuthMethod alloc] initWithAuthEndpoint:@"https://your.authendpoint/pusher/auth"];
OCPusherHost *host = [[OCPusherHost alloc] initWithCluster:@"eu"];
PusherClientOptions *options = [[PusherClientOptions alloc]
                                initWithOcAuthMethod:authMethod
                                autoReconnect:YES
                                ocHost:host
                                port:nil
                                useTLS:YES
                                activityTimeout:nil];
pusher = [[Pusher alloc] initWithAppKey:@"YOUR_APP_KEY" options:options];

As you may have noticed, this differs slightly for Objective-C usage. The main changes are that you need to use OCAuthMethod and OCPusherHost in place of AuthMethod and PusherHost. The OCAuthMethod class has the following functions that you can call in your Objective-C code.

public init(authEndpoint: String)

public init(authRequestBuilder: AuthRequestBuilderProtocol)

public init(secret: String)

public init()
OCAuthMethod *authMethod = [[OCAuthMethod alloc] initWithSecret:@"YOUR_APP_SECRET"];
PusherClientOptions *options = [[PusherClientOptions alloc] initWithAuthMethod:authMethod];

The case is similar for OCPusherHost. You have the following functions available:

public init(host: String)

public init(cluster: String)
[[OCPusherHost alloc] initWithCluster:@"YOUR_CLUSTER_SHORTCODE"];

Authenticated channel example:

Swift

class AuthRequestBuilder: AuthRequestBuilderProtocol {
    func requestFor(socketID: String, channelName: String) -> URLRequest? {
        var request = URLRequest(url: URL(string: "http://localhost:9292/builder")!)
        request.httpMethod = "POST"
        request.httpBody = "socket_id=\(socketID)&channel_name=\(channel.name)".data(using: String.Encoding.utf8)
        request.addValue("myToken", forHTTPHeaderField: "Authorization")
        return request
    }
}

let options = PusherClientOptions(
    authMethod: AuthMethod.authRequestBuilder(authRequestBuilder: AuthRequestBuilder())
)
let pusher = Pusher(
  key: "APP_KEY",
  options: options
)

Objective-C

@interface AuthRequestBuilder : NSObject <AuthRequestBuilderProtocol>

- (NSURLRequest *)requestForSocketID:(NSString *)socketID channelName:(NSString *)channelName;

@end

@implementation AuthRequestBuilder

- (NSURLRequest *)requestForSocketID:(NSString *)socketID channelName:(NSString *)channelName {
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[[NSURL alloc] initWithString:@"http://localhost:9292/pusher/auth"]];
    NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL: [[NSURL alloc] initWithString:@"http://localhost:9292/pusher/auth"]];

    NSString *dataStr = [NSString stringWithFormat: @"socket_id=%@&channel_name=%@", socketID, channelName];
    NSData *data = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
    mutableRequest.HTTPBody = data;
    mutableRequest.HTTPMethod = @"POST";
    [mutableRequest addValue:@"myToken" forHTTPHeaderField:@"Authorization"];

    request = [mutableRequest copy];

    return request;
}

@end

OCAuthMethod *authMethod = [[OCAuthMethod alloc] initWithAuthRequestBuilder:[[AuthRequestBuilder alloc] init]];
PusherClientOptions *options = [[PusherClientOptions alloc] initWithAuthMethod:authMethod];

Where "Authorization" and "myToken" are the field and value your server is expecting in the headers of the request.

Connection

A Websocket connection is established by providing your API key to the constructor function:

Swift

let pusher = Pusher(key: "APP_KEY")
pusher.connect()

Objective-C

Pusher *pusher = [[Pusher alloc] initWithAppKey:@"YOUR_APP_KEY"];
[pusher connect];

This returns a client object which can then be used to subscribe to channels and then calling connect() triggers the connection process to start.

Important: You must keep a strong reference to the Pusher client. You could achieve that by making pusher a property of your app delegate, for example.

You can also set a userDataFetcher on the connection object.

  • userDataFetcher (() -> PusherPresenceChannelMember) - if you are subscribing to an authenticated channel and wish to provide a function to return user data

You set it like this:

Swift

let pusher = Pusher(key: "APP_KEY")

pusher.connection.userDataFetcher = { () -> PusherPresenceChannelMember in
    return PusherPresenceChannelMember(userId: "123", userInfo: ["twitter": "hamchapman"])
}

Objective-C

Pusher *pusher = [[Pusher alloc] initWithAppKey:@"YOUR_APP_KEY"];

pusher.connection.userDataFetcher = ^PusherPresenceChannelMember* () {
    NSString *uuid = [[NSUUID UUID] UUIDString];
    return [[PusherPresenceChannelMember alloc] initWithUserId:uuid userInfo:nil];
};

Connection delegate

There is a PusherDelegate that you can use to get notified of connection-related information. These are the functions that you can optionally implement when conforming to the PusherDelegate protocol:

@objc optional func changedConnectionState(from old: ConnectionState, to new: ConnectionState)
@objc optional func subscribedToChannel(name: String)
@objc optional func failedToSubscribeToChannel(name: String, response: URLResponse?, data: String?, error: NSError?)
@objc optional func debugLog(message: String)
@objc(receivedError:) optional func receivedError(error: PusherError)
@objc optional func failedToDecryptEvent(eventName: String, channelName: String, data: String?)

The names of the functions largely give away what their purpose is but just for completeness:

  • changedConnectionState - use this if you want to use connection state changes to perform different actions / UI updates
  • subscribedToChannel - use this if you want to be informed of when a channel has successfully been subscribed to, which is useful if you want to perform actions that are only relevant after a subscription has succeeded, e.g. logging out the members of a presence channel
  • failedToSubscribeToChannel - use this if you want to be informed of a failed subscription attempt, which you could use, for example, to then attempt another subscription or make a call to a service you use to track errors
  • debugLog - use this if you want to log Pusher-related events, e.g. the underlying websocket receiving a message
  • receivedError - use this if you want to be informed of errors received from Pusher Channels e.g. Application is over connection quota. You can find some of the possible errors listed here.
  • failedToDecryptEvent - only used with private encrypted channels - use this if you want to be notified if any messages fail to decrypt.

Setting up a delegate looks like this:

Swift

class ViewController: UIViewController, PusherDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        let pusher = Pusher(key: "APP_KEY")
        pusher.connection.delegate = self
        // ...
    }
}

Objective-C

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.client = [[Pusher alloc] initWithAppKey:@"YOUR_APP_KEY"];

    self.client.connection.delegate = self;
    // ...
}

Here are examples of setting up a class with functions for each of the optional protocol functions:

Swift

class DummyDelegate: PusherDelegate {
    func changedConnectionState(from old: ConnectionState, to new: ConnectionState) {
        // ...
    }

    func debugLog(message: String) {
        // ...
    }

    func subscribedToChannel(name: String) {
        // ...
    }

    func failedToSubscribeToChannel(name: String, response: URLResponse?, data: String?, error: NSError?) {
        // ...
    }

    func receivedError(error: PusherError) {
        let message = error.message
        if let code = error.code {
            // ...
        }
    }

    func failedToDecryptEvent(eventName: String, channelName: String, data: String?) {
      // ...
    }

}

Objective-C

@interface DummyDelegate : NSObject <PusherDelegate>

- (void)changedConnectionState:(enum ConnectionState)old to:(enum ConnectionState)new_
- (void)debugLogWithMessage:(NSString *)message
- (void)subscribedToChannelWithName:(NSString *)name
- (void)failedToSubscribeToChannelWithName:(NSString *)name response:(NSURLResponse *)response data:(NSString *)data error:(NSError *)error
- (void)receivedError:(PusherError *)error
- (void)failedToDecryptEventWithEventName:(NSString *)eventName channelName:(NSString *)channelName data:(NSString *)data

@end

@implementation DummyDelegate

- (void)changedConnectionState:(enum ConnectionState)old to:(enum ConnectionState)new_ {
    // ...
}

- (void)debugLogWithMessage:(NSString *)message {
    // ...
}

- (void)subscribedToChannelWithName:(NSString *)name {
    // ...
}

- (void)failedToSubscribeToChannelWithName:(NSString *)name response:(NSURLResponse *)response data:(NSString *)data error:(NSError *)error {
    // ...
}

- (void)receivedError:(PusherError *)error {
    NSNumber *code = error.codeOC;
    NSString *message = error.message;
    // ...
}

- (void)failedToDecryptEventWithEventName:(NSString *)eventName channelName:(NSString *)channelName data:(NSString *)data {
  // ...
}

@end

The different states that the connection can be in are (Objective-C integer enum cases in brackets):

  • connecting (0) - the connection is about to attempt to be made
  • connected (1) - the connection has been successfully made
  • disconnecting (2) - the connection has been instructed to disconnect and it is just about to do so
  • disconnected (3) - the connection has disconnected and no attempt will be made to reconnect automatically
  • reconnecting (4) - an attempt is going to be made to try and re-establish the connection

There is a stringValue() function that you can call on ConnectionState objects in order to get a String representation of the state, for example "connecting".

Reconnection

There are three main ways in which a disconnection can occur:

  • The client explicitly calls disconnect and a close frame is sent over the websocket connection
  • The client experiences some form of network degradation which leads to a heartbeat (ping/pong) message being missed and thus the client disconnects
  • The Pusher server closes the websocket connection; typically this will only occur during a restart of the Pusher socket servers and an almost immediate reconnection should occur

In the case of the first type of disconnection the library will (as you'd hope) not attempt a reconnection.

The library uses NWWebSocket which attempts to detect network degradation events that lead to disconnection. If this is detected then the library will attempt to reconnect (by default) with an exponential backoff, indefinitely (the maximum time between reconnect attempts is, by default, capped at 120 seconds). The value of reconnectAttemptsMax is a public property on the PusherConnection and so can be changed if you wish to set a maximum number of reconnect attempts.

If the Pusher servers close the websocket, or if a disconnection happens due to network events that aren't covered by NWWebSocket, then the library will still attempt to reconnect as described above.

All of this is the case if you have the client option of autoReconnect set as true, which it is by default. If the reconnection strategies are not suitable for your use case then you can set autoReconnect to false and implement your own reconnection strategy based on the connection state changes.

N.B: If the Pusher servers close the websocket with a Channels Protocol closure code, then the autoReconnect option is ignored, and the reconnection strategy is determined by the specific closure code that was received.

There are a couple of properties on the connection (PusherConnection) that you can set that affect how the reconnection behavior works. These are:

  • public var reconnectAttemptsMax: Int? = 6 - if you set this to nil then there is no maximum number of reconnect attempts and so attempts will continue to be made with an exponential backoff (based on number of attempts), otherwise only as many attempts as this property's value will be made before the connection's state moves to .disconnected
  • public var maxReconnectGapInSeconds: Double? = nil - if you want to set a maximum length of time (in seconds) between reconnect attempts then set this property appropriately

Note that the number of reconnect attempts gets reset to 0 as soon as a successful connection is made.

Subscribing

Public channels

The default method for subscribing to a channel involves invoking the subscribe method of your client object:

Swift

let myChannel = pusher.subscribe("my-channel")

Objective-C

PusherChannel *myChannel = [pusher subscribeWithChannelName:@"my-channel"];

This returns PusherChannel object, which events can be bound to.

For non-presence channels, you can also provide a function that will be called when a client either subscribes or unsubscribes to a channel with the number of subscribers as a parameter. Also, this function is available as a parameter to subscribe function.

let onSubscriptionCountChanged = { (count: Int) in
    print("\(count) subscriptions")
}

let channel = pusher.subscribe(
    channelName: "my-channel",
    onSubscriptionCountChanged: onSubscriptionCountChanged
)

Private channels

Private channels are created in exactly the same way as public channels, except that they reside in the 'private-' namespace. This means prefixing the channel name:

Swift

let myPrivateChannel = pusher.subscribe("private-my-channel")

Objective-C

PusherChannel *myPrivateChannel = [pusher subscribeWithChannelName:@"private-my-channel"];

Subscribing to private channels involves the client being authenticated. See the Configuration section for the authenticated channel example for more information.

Private encrypted channels

Similar to Private channels, you can also subscribe to a private encrypted channel. This library now fully supports end-to-end encryption. This means that only you and your connected clients will be able to read your messages. Pusher cannot decrypt them.

Like with private channels, you must provide an authentication endpoint. That endpoint must be using a server client that supports end-to-end encryption. There is a demonstration endpoint to look at using nodejs.

The shared secret used to decrypt events is loaded from the same auth endpoint request that is used to authorize your subscription. There is also a mechanism for reloading the shared secret if your encryption master key changes. If an event is encountered that cannot be decrypted, a request is made to your auth endpoint to attempt to load the new shared secret. If that request fails or if the returned secret still cannot decrypt the event then that event will be skipped, the failedToDecryptEvent connection delegate function will be called, and the next received event will be processed.

Because of the requirement to reload the shared secret on demand, you can only use the following auth methods: endpoint, authRequestBuilder, authorizer. It is not possible to pass an instance of PusherAuth to the subscribe function if you are subscribing to an encrypted channel.

Limitations

  • Is not safe for use in extensions
  • Client events are not supported on encrypted channels

Swift

let privateEncryptedChannel = pusher.subscribe(channelName: "private-encrypted-my-channel")

Objective-C

PusherChannel *privateEncryptedChannel = [pusher subscribeWithChannelName:@"private-encrypted-my-channel"];

There is also an optional callback in the connection delegate when you can listen for any failed decryption events:

optional func failedToDecryptEvent(eventName: String, channelName: String, data: String?)

Presence channels

Presence channels are channels whose names are prefixed by presence-.

The recommended way of subscribing to a presence channel is to use the subscribeToPresenceChannel function, as opposed to the standard subscribe function. Using the subscribeToPresenceChannel function means that you get a PusherPresenceChannel object returned, as opposed to a standard PusherChannel. This PusherPresenceChannel object has some extra, presence-channel-specific functions available to it, such as members, me, and findMember.

Swift

let myPresenceChannel = pusher.subscribeToPresenceChannel(channelName: "presence-my-channel")

Objective-C

PusherPresenceChannel *myPresenceChannel = [pusher subscribeToPresenceChannelWithChannelName:@"presence-my-channel"];

As alluded to, you can still subscribe to presence channels using the subscribe method, but the channel object you get back won't have access to the presence-channel-specific functions, unless you choose to cast the channel object to a PusherPresenceChannel.

Swift

let myPresenceChannel = pusher.subscribe("presence-my-channel")

Objective-C

PusherChannel *myPresenceChannel = [pusher subscribeWithChannelName:@"presence-my-channel"];

You can also provide functions that will be called when members are either added to or removed from the channel. These are available as parameters to both subscribe and subscribeToPresenceChannel.

Swift

let onMemberChange = { (member: PusherPresenceChannelMember) in
    print(member)
}

let chan = pusher.subscribeToPresenceChannel("presence-channel", onMemberAdded: onMemberChange, onMemberRemoved: onMemberChange)

Objective-C

void (^onMemberChange)(PusherPresenceChannelMember*) = ^void (PusherPresenceChannelMember *member) {
    NSLog(@"%@", member);
};

PusherChannel *myPresenceChannel = [pusher subscribeWithChannelName:@"presence-my-channel" onMemberAdded:onMemberChange onMemberRemoved:onMemberChange];

Note: The members and myId properties of PusherPresenceChannel objects (and functions that get the value of these properties) will only be set once subscription to the channel has succeeded.

The easiest way to find out when a channel has been successfully subscribed to is to bind to the event named pusher:subscription_succeeded on the channel you're interested in. It would look something like this:

Swift

let pusher = Pusher(key: "YOUR_APP_KEY")

let chan = pusher.subscribeToPresenceChannel("presence-channel")

chan.bind(eventName: "pusher:subscription_succeeded", eventCallback: { event in
    print("Subscribed!")
    print("I can now access myId: \(chan.myId)")
    print("And here are the channel members: \(chan.members)")
})

Objective-C

Pusher *pusher = [[Pusher alloc] initWithAppKey:@"YOUR_APP_KEY"];
PusherPresenceChannel *chan = [pusher subscribeToPresenceChannelWithChannelName:@"presence-channel"];

[chan bindWithEventName:@"pusher:subscription_succeeded" eventCallback: ^void (PusherEvent *event) {
    NSLog(@"Subscribed!");
    NSLog(@"I can now access myId: %@", chan.myId);
    NSLog(@"And here are my channel members: %@", chan.members);
}];

You can also be notified of a successful subscription by using the subscriptionDidSucceed delegate method that is part of the PusherDelegate protocol.

Here is an example of using the delegate:

Swift

class DummyDelegate: PusherDelegate {
    func subscribedToChannel(name: String) {
        if channelName == "presence-channel" {
            if let presChan = pusher.connection.channels.findPresence(channelName) {
                // in here you can now have access to the channel's members and myId properties
                print(presChan.members)
                print(presChan.myId)
            }
        }
    }
}

let pusher = Pusher(key: "YOUR_APP_KEY")
pusher.connection.delegate = DummyDelegate()
let chan = pusher.subscribeToPresenceChannel("presence-channel")

Objective-C

@implementation DummyDelegate

- (void)subscribedToChannelWithName:(NSString *)name {
    if ([channelName isEqual: @"presence-channel"]) {
        PusherPresenceChannel *presChan = [self.client.connection.channels findPresenceWithName:@"presence-channel"];
        NSLog(@"%@", [presChan members]);
        NSLog(@"%@", [presChan myId]);
    }
}

@implementation ViewController

- (void)viewDidLoad {
    // ...

    Pusher *pusher = [[Pusher alloc] initWithAppKey:@"YOUR_APP_KEY"];
    pusher.connection.delegate = [[DummyDelegate alloc] init];
    PusherChannel *chan = [pusher subscribeToPresenceChannelWithChannelName:@"presence-channel"];

Note that both private and presence channels require the user to be authenticated in order to subscribe to the channel. This authentication can either happen inside the library, if you configured your Pusher object with your app's secret, or an authentication request is made to an authentication endpoint that you provide, again when instantiating your Pusher object.

We recommend that you use an authentication endpoint over including your app's secret in your app in the vast majority of use cases. If you are completely certain that there's no risk to you including your app's secret in your app, for example if your app is just for internal use at your company, then it can make things easier than setting up an authentication endpoint.

Subscribing with self-provided auth values

It is possible to subscribe to channels that require authentication by providing the auth information at the point of calling subscribe or subscribeToPresenceChannel. This is done as shown below:

Swift

let pusherAuth = PusherAuth(auth: yourAuthString, channelData: yourOptionalChannelDataString)
let chan = self.pusher.subscribe(channelName, auth: pusherAuth)

This PusherAuth object can be initialized with just an auth (String) value if the subscription is to a private channel, or both an auth (String) and channelData (String) pair of values if the subscription is to a presence channel.

These auth and channelData values are the values that you received if the json object created by a call to pusher.authenticate(...) in one of our various server libraries.

Keep in mind that in order to generate a valid auth value for a subscription the socketId (i.e. the unique identifier for a web socket connection to the Pusher servers) must be present when the auth value is generated. As such, the likely flow for using this is something like this would involve checking for when the connection state becomes connected before trying to subscribe to any channels requiring authentication.

Binding to events

Events can be bound to at 2 levels; globally and per channel. When binding to an event you can choose to save the return value, which is a unique identifier for the event handler that gets created. The only reason to save this is if you're going to want to unbind from the event at a later point in time. There is an example of this below.

Per-channel events

These are bound to a specific channel, and mean that you can reuse event names in different parts of your client application.

Swift

let pusher = Pusher(key: "YOUR_APP_KEY")
let myChannel = pusher.subscribe("my-channel")

myChannel.bind(eventName: "new-price", eventCallback: { (event: PusherEvent) -> Void in
    if let data: String = event.data {
        // `data` is a string that you can parse if necessary.
    }
})

The callback is passed a PusherEvent (see docs).

View legacy approach
let pusher = Pusher(key: "YOUR_APP_KEY")
let myChannel = pusher.subscribe("my-channel")

myChannel.bind(eventName: "new-price", callback: { (data: Any?) -> Void in
    if let data = data as? [String : AnyObject] {
        if let price = data["price"] as? String, company = data["company"] as? String {
            print("\(company) is now priced at \(price)")
        }
    }
})

Objective-C

Pusher *pusher = [[Pusher alloc] initWithAppKey:@"YOUR_APP_KEY"];
PusherChannel *chan = [pusher subscribeWithChannelName:@"my-channel"];

[chan bindWithEventName:@"new-price" eventCallback:^void (PusherEvent *event) {
    NSString *data = event.data;
    // `data` is a string that you can parse if necessary.
}];
View legacy approach
Pusher *pusher = [[Pusher alloc] initWithAppKey:@"YOUR_APP_KEY"];
PusherChannel *chan = [pusher subscribeWithChannelName:@"my-channel"];

[chan bindWithEventName:@"new-price" callback:^void (NSDictionary *data) {
    NSString *price = data[@"price"];
    NSString *company = data[@"company"];

    NSLog(@"%@ is now priced at %@", company, price);
}];

Global events

You can attach behavior to these events regardless of the channel the event is broadcast to.

Swift

let pusher = Pusher(key: "YOUR_APP_KEY")
pusher.subscribe("my-channel")

pusher.bind(eventCallback: { (event: PusherEvent) -> Void in
    if let data: String = event.data {
        // `data` is a string that you can parse if necessary.
    }
})

The callback is passed a PusherEvent (see docs).

View legacy approach
let pusher = Pusher(key: "YOUR_APP_KEY")
pusher.subscribe("my-channel")

pusher.bind(callback: { (event: Any?) -> Void in
    if let data = event["data"] as? [String : AnyObject] {
        if let commenter = data["commenter"] as? String, message = data["message"] as? String {
            print("\(commenter) wrote \(message)")
        }
    }
})

Objective-C

Pusher *pusher = [[Pusher alloc] initWithAppKey:@"YOUR_APP_KEY"];
PusherChannel *chan = [pusher subscribeWithChannelName:@"my-channel"];

[pusher bindWithEventCallback: ^void (PusherEvent *event) {
    // `data` is a string that you can parse if necessary.
    NSString *data = event.data;
}];
View legacy approach
Pusher *pusher = [[Pusher alloc] initWithAppKey:@"YOUR_APP_KEY"];
PusherChannel *chan = [pusher subscribeWithChannelName:@"my-channel"];

[pusher bind: ^void (NSDictionary *event) {
    NSDictionary *data = event[@"data"];
    NSString *commenter = data[@"commenter"];
    NSString *message = data[@"message"];

    NSLog(@"%@ wrote %@", commenter, message);
}];

Callback parameters

PusherEvent

The callbacks you bind receive a PusherEvent:

Property Type Description
eventName String The name of the event.
channelName String? The name of the channel that the event was triggered on.
data String? The data that was passed to trigger, encoded as a string. If you passed an object then that will have been serialized to a JSON string which you can parse as necessary. See parsing event data.
userId String? The ID of the user who triggered the event. This is only available for client events triggered on presence channels.
Function Parameters Return Type Description
property withKey: String - The key of the property Any? A helper function for accessing raw properties from the websocket event. Data returned by this function should not be considered stable and it is recommended that you use the properties above instead.

Parsing event data

The data property of PusherEvent contains the string representation of the data that you passed when you triggered the event. If you passed an object then that object will have been serialized to JSON. You can parse that JSON as appropriate. You can make use of JSONSerialization, or you can use the JSONDecoder to decode the JSON into a Codable Class or Struct. See the Apple docs: Encoding and Decoding Custom Types.

For example, the following might be an example of a stock tracking app publishing price updates for companies. You can decode the "price-update" event into a struct in Swift:

struct PriceUpdate: Codable {
    public let company: String,
    public let price: Int,
}

let pusher = Pusher(key: "YOUR_APP_KEY")
let myChannel = pusher.subscribe("my-channel")
let decoder = JSONDecoder()

myChannel.bind(eventName: "price-update", eventCallback: { (event: PusherEvent) -> Void in
    guard let json: String = event.data,
        let jsonData: Data = json.data(using: .utf8)
    else{
        print("Could not convert JSON string to data")
        return
    }

    let decoded = try? decoder.decode(PriceUpdate.self, from: jsonData)
    guard let priceUpdate = decoded else {
        print("Could not decode price update")
        return
    }

    print("\(priceUpdate.company) is now priced at \(priceUpdate.price)")
})

Alternatively, you could use JSONSerialization to decode the JSON into Swift data types:

Swift

let pusher = Pusher(key: "YOUR_APP_KEY")
let myChannel = pusher.subscribe("my-channel")

myChannel.bind(eventName: "price-update", eventCallback: { (event: PusherEvent) -> Void in
    guard let json: String = event.data,
        let jsonData: Data = json.data(using: .utf8)
    else{
        print("Could not convert JSON string to data")
        return
    }

    let decoded = try? JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any]
    guard let priceUpdate = decoded else {
        print("Could not decode price update")
        return
    }

    if let company = priceUpdate["company"] as? String, let price = priceUpdate["price"] as? String {
        print("\(company) is now priced at \(price)")
    }
})

Objective-C

Pusher *pusher = [[Pusher alloc] initWithAppKey:@"YOUR_APP_KEY"];
PusherChannel *chan = [pusher subscribeWithChannelName:@"my-channel"];

[chan bindWithEventName:@"price-update" eventCallback:^void (PusherEvent *event) {
    NSString *dataString = event.data;
    NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];

    NSError *error;
    NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

    NSString *price = jsonObject[@"price"];
    NSString *company = jsonObject[@"company"];

    NSLog(@"%@ is now priced at %@", company, price);
}];

Receiving errors

Errors received from Pusher Channels can be accessed via the connection delegate. This was previously done by binding callbacks.

View legacy approach

Errors are sent to the client for which they are relevant with an event name of pusher:error. These can be received and handled using code as follows. Obviously the specifics of how to handle them are left up to the developer but this displays the general pattern.

Swift

pusher.bind({ (message: Any?) in
    if let message = message as? [String: AnyObject], eventName = message["event"] as? String where eventName == "pusher:error" {
        if let data = message["data"] as? [String: AnyObject], errorMessage = data["message"] as? String {
            print("Error message: \(errorMessage)")
        }
    }
})

Objective-C

[pusher bind:^void (NSDictionary *data) {
    NSString *eventName = data[@"event"];

    if ([eventName isEqualToString:@"pusher:error"]) {
        NSString *errorMessage = data[@"data"][@"message"];
        NSLog(@"Error message: %@", errorMessage);
    }
}];

The sort of errors you might get are:

# if attempting to subscribe to an already subscribed-to channel

"{\"event\":\"pusher:error\",\"data\":{\"code\":null,\"message\":\"Existing subscription to channel presence-channel\"}}"

# if the auth signature generated by your auth mechanism is invalid

"{\"event\":\"pusher:error\",\"data\":{\"code\":null,\"message\":\"Invalid signature: Expected HMAC SHA256 hex digest of 200557.5043858:presence-channel:{\\\"user_id\\\":\\\"200557.5043858\\\"}, but got 8372e1649cf5a45a2de3cd97fe11d85de80b214243e3a9e9f5cee502fa03f880\"}}"

You can see that the general form they take is:

{
  "event": "pusher:error",
  "data": {
    "code": null,
    "message": "Error message here"
  }
}

Unbind event handlers

You can remove previously-bound handlers from an object by using the unbind function. For example,

Swift

let pusher = Pusher(key: "YOUR_APP_KEY")
let myChannel = pusher.subscribe("my-channel")

let eventHandlerId = myChannel.bind(eventName: "new-price", eventCallback: { (event: PusherEvent) -> Void in
  //...
})

myChannel.unbind(eventName: "new-price", callbackId: eventHandlerId)

Objective-C

Pusher *pusher = [[Pusher alloc] initWithAppKey:@"YOUR_APP_KEY"];
PusherChannel *chan = [pusher subscribeWithChannelName:@"my-channel"];

NSString *callbackId = [chan bindWithEventName:@"new-price" eventCallback:^void (PusherEvent *event) {
    //...
}];

[chan unbindWithEventName:@"new-price" callbackId:callbackId];

You can unbind from events at both the global and per channel level. For both objects you also have the option of calling unbindAll, which, as you can guess, will unbind all eventHandlers on the object.

Triggering events

Once a private or presence subscription has been authorized (see authenticating users) and the subscription has succeeded, it is possible to trigger events on those channels.

chan.trigger(eventName: "client-myEvent", data: ["myName": "Bob"])

Events triggered by clients are called client events. Because they are being triggered from a client which may not be trusted there are a number of enforced rules when using them. Some of these rules include:

  • Event names must have a client- prefix
  • Rate limits
  • You can only trigger an event when the subscription has succeeded

For full details see the client events documentation.

Testing

There are a set of tests for the library that can be run using the standard method (Command-U in Xcode).

The tests also get run on Github Actions, see CI Action

Extensions

Communication

  • If you have found a bug, please open an issue.
  • If you have a feature request, please open an issue.
  • If you want to contribute, please submit a pull request (preferably with some tests ๐Ÿ™‚ ).

Credits

PusherSwift is owned and maintained by Pusher. It was originally created by Hamilton Chapman.

It uses code from the following repositories:

The individual licenses for these libraries are included in the corresponding Swift files.

License

PusherSwift is released under the MIT license. See LICENSE for details.

More Repositories

1

pusher-js

Pusher Javascript library
JavaScript
1,970
star
2

atom-pair

An Atom package that allows for epic pair programming
JavaScript
1,454
star
3

pusher-http-php

PHP library for interacting with the Pusher Channels HTTP API
PHP
1,355
star
4

pusher-http-ruby

Ruby library for Pusher Channels HTTP API
Ruby
659
star
5

libPusher

An Objective-C interface to Pusher Channels
C
409
star
6

pusher-http-laravel

[DEPRECATED] A Pusher Channels bridge for Laravel
PHP
405
star
7

pusher-http-python

Pusher Channels HTTP API library for Python
Python
368
star
8

k8s-spot-rescheduler

Tries to move K8s Pods from on-demand to spot instances
Go
311
star
9

pusher-websocket-java

Pusher Channels client library for Java targeting general Java and Android
Java
302
star
10

build-a-slack-clone-with-react-and-pusher-chatkit

In this tutorial, you'll learn how to build a chat app with React, complete with typing indicators, online status, and more.
JavaScript
235
star
11

pusher-angular

Pusher Angular Library | owner=@leesio
JavaScript
233
star
12

pusher-http-go

Pusher Channels HTTP API library for Go
Go
196
star
13

k8s-spot-termination-handler

Monitors AWS for spot termination notices when run on spot instances and shuts down gracefully
Makefile
118
star
14

NWWebSocket

A WebSocket client written in Swift, using the Network framework from Apple.
Swift
112
star
15

go-interface-fuzzer

Automate the boilerplate of fuzz testing Go interfaces | owner: @willsewell
Go
110
star
16

pusher-http-dotnet

.NET library for interacting with the Pusher HTTP API
C#
109
star
17

k8s-auth-example

Example Kubernetes Authentication helper. Performs OIDC login and configures Kubectl appropriately.
Go
108
star
18

pusher-websocket-dotnet

Pusher Channels Client Library for .NET
C#
107
star
19

faros

Faros is a CRD based GitOps controller
Go
100
star
20

backbone-todo-app

JavaScript
92
star
21

chatkit-client-js

JavaScript client SDK for Pusher Chatkit
JavaScript
89
star
22

quack

In-Cluster templating for Kubernetes manifests
Go
70
star
23

pusher-channels-flutter

Pusher Channels client library for Flutter targeting IOS, Android, and WEB
Dart
67
star
24

websockets-from-scratch-tutorial

Tutorial that shows how to implement a websocket server using Ruby's built-in libs
Ruby
60
star
25

backpusher

JavaScript
54
star
26

push-notifications-php

Pusher Beams PHP Server SDK
PHP
54
star
27

chatkit-android

Android client SDK for Pusher Chatkit
Kotlin
54
star
28

pusher-websocket-react-native

React Native official Pusher SDK
TypeScript
53
star
29

django-pusherable

Real time notification when an object view is accessed via Pusher
Python
52
star
30

notify

Ruby
51
star
31

cli

A CLI for Pusher (beta)
Go
50
star
32

k8s-spot-price-monitor

Monitors the spot prices of instances in a Kubernetes cluster and exposes them as prometheus metrics
Python
44
star
33

chatkit-command-line-chat

A CLI chat, built with Chatkit
JavaScript
41
star
34

pusher-http-java

Java client to interact with the Pusher HTTP API
Java
40
star
35

chatkit-swift

Swift SDK for Pusher Chatkit
Swift
40
star
36

electron-desktop-chat

A desktop chat built with React, React Desktop and Electron
JavaScript
39
star
37

push-notifications-web

Beams Browser notifications
JavaScript
38
star
38

crank

Process slow restarter
Go
37
star
39

pusher-websocket-android

Library built on top of pusher-websocket-java for Android. Want Push Notifications? Check out Pusher Beams!
Java
35
star
40

chameleon

A collection of front-end UI components used across Pusher โœจ
CSS
35
star
41

chatkit-server-php

PHP SDK for Pusher Chatkit
PHP
35
star
42

cide

Isolated test runner with Docker
Ruby
33
star
43

push-notifications-swift

Swift SDK for the Pusher Beams product:
Swift
33
star
44

pusher-phonegap-android

JavaScript
30
star
45

push-notifications-python

Pusher Beams Python Server SDK
Python
30
star
46

pusher-websocket-unity

Pusher Channels Unity Client Library
C#
27
star
47

hacktoberfest

24
star
48

laravel-chat

PHP
22
star
49

push-notifications-android

Android SDK for Pusher Beams
Kotlin
21
star
50

push-notifications-node

Pusher Beams Node.js Server SDK
JavaScript
20
star
51

pusher-test-iOS

iOS app for developers to test connections to Pusher
Objective-C
19
star
52

push-notifications-ruby

Pusher Beams Ruby Server SDK
Ruby
19
star
53

chatkit-server-node

Node.js SDK for Pusher Chatkit
TypeScript
16
star
54

rack-headers_filter

Remove untrusted headers from Rack requests | owner=@zimbatm
Ruby
15
star
55

pusher-test-android

Test and diagnostic app for Android, based on pusher-java-client
Java
14
star
56

pusher-realtime-tfl-cameras

Realtime TfL Traffic Camera API, powered by Pusher
JavaScript
14
star
57

buddha

Buddha command execution and health checking | owner: @willsewell
Go
14
star
58

chatkit-server-go

Chatkit server SDK for Golang
Go
13
star
59

pusher-channels-auth-example

A simple server exposing a pusher auth endpoint
JavaScript
13
star
60

pusher-platform-js

Pusher Platform client library for browsers and react native
TypeScript
13
star
61

stronghold

[DEPRECATED] A configuration service | owner: @willsewell
Haskell
12
star
62

pusher-twilio-example

CSS
12
star
63

prom-rule-reloader

Watches configmaps for prometheus rules and keeps prometheus in-sync
Go
12
star
64

sample-chatroom-ios-chatkit

How to make an iOS Chatroom app using Swift and Chatkit
PHP
11
star
65

electron-desktop-starter-template

JavaScript
11
star
66

chatkit-server-ruby

Ruby server SDK for Chatkit
Ruby
11
star
67

realtime-visitor-tracker

Realtime location aware visitor tracker for a web site or application
PHP
11
star
68

push-notifications-server-java

Pusher Beams Java Server SDK
Kotlin
10
star
69

android-slack-clone

Android chat application, built with Chatkit
Kotlin
10
star
70

filtrand

JavaScript
10
star
71

vault

Front-end pattern library
Ruby
9
star
72

push-notifications-go

Pusher Beams Go Server SDK
Go
9
star
73

pusher-platform-android

Pusher Platform SDK for Android
Kotlin
9
star
74

git-store

Go git abstraction for use in Kubernetes Controllers
Go
8
star
75

pusher-platform-swift

Swift SDK for Pusher platform products
Swift
8
star
76

realtime_survey_complete

JavaScript
8
star
77

docs

The all new Pusher docs, powered by @11ty and @vercel
CSS
8
star
78

push-notifications-server-swift

Pusher Beams Swift Server SDK
Swift
8
star
79

pusher-python-rest

Python client to interact with the Pusher REST API. DEPRECATED in favour of https://github.com/pusher/pusher-http-python
Python
8
star
80

real-time-progress-bar-tutorial

Used inthe realtime progress bar tutorial blog post - http://blog.pusher.com
JavaScript
7
star
81

pusher-channels-chunking-example

HTML
7
star
82

pusher-http-swift

Swift library for interacting with the Pusher Channels HTTP API
Swift
7
star
83

feeds-client-js

JS client for Pusher Feeds
JavaScript
6
star
84

pusher-test

Simple website which allows manual testing of pusher-js versions
JavaScript
6
star
85

java-websocket

A fork of https://github.com/TooTallNate/Java-WebSocket | owner=@zmarkan
HTML
6
star
86

bridge-troll

A Troll that ensures files don't change
Go
5
star
87

navarchos

Node replacing controller
Go
5
star
88

realtime-notifications-tutorial

Create realtime notifications in minutes, not days =)
4
star
89

pusher-socket-protocol

Protocol for pusher sockets
HTML
4
star
90

icanhazissues

Github issues kanban
JavaScript
4
star
91

textsync-server-node

[DEPRECATED] A node.js library to simplify token generation for TextSync authorization endpoints.
TypeScript
4
star
92

pusher_tutorial_realtimeresults

JavaScript
3
star
93

pusher-js-diagnostics

JavaScript
3
star
94

react-rest-api-tutorial

Accompanying tutorial for consuming RESTful APIs in React
CSS
3
star
95

testing

Configuration for Pusher's Open Source Prow instance
Go
3
star
96

feeds-server-node

The server Node SDK for Pusher Feeds
JavaScript
3
star
97

spacegame_example

Simple example of a space game using node.js and Pusher
JavaScript
3
star
98

chatkit-quickstart-swift

A project to get started with Chatkit.
Swift
2
star
99

pusher-whos-in

Ruby
2
star
100

chatkit-android-public-demo

This will hold the demo app for chatkit android. Owner: @daniellevass
Kotlin
2
star