{"id":13462657,"url":"https://github.com/pusher/pusher-websocket-swift","last_synced_at":"2025-12-29T23:05:17.687Z","repository":{"id":27542583,"uuid":"31024079","full_name":"pusher/pusher-websocket-swift","owner":"pusher","description":"Pusher Channels websocket library for Swift","archived":false,"fork":false,"pushed_at":"2024-12-12T13:28:08.000Z","size":3369,"stargazers_count":277,"open_issues_count":15,"forks_count":170,"subscribers_count":28,"default_branch":"master","last_synced_at":"2025-03-16T08:46:03.007Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://pusher.com/channels","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/pusher.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2015-02-19T16:18:34.000Z","updated_at":"2025-03-04T20:36:55.000Z","dependencies_parsed_at":"2024-01-16T05:09:33.765Z","dependency_job_id":"4c19c7c1-1322-49d5-a0ee-84054a98bccb","html_url":"https://github.com/pusher/pusher-websocket-swift","commit_stats":{"total_commits":808,"total_committers":53,"mean_commits":"15.245283018867925","dds":0.5631188118811881,"last_synced_commit":"886341f9dad453c9822f2525136ee2006a6c3c9e"},"previous_names":[],"tags_count":62,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pusher%2Fpusher-websocket-swift","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pusher%2Fpusher-websocket-swift/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pusher%2Fpusher-websocket-swift/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pusher%2Fpusher-websocket-swift/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/pusher","download_url":"https://codeload.github.com/pusher/pusher-websocket-swift/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245407471,"owners_count":20610226,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T13:00:18.274Z","updated_at":"2025-12-29T23:05:17.675Z","avatar_url":"https://github.com/pusher.png","language":"Swift","funding_links":[],"categories":["Socket"],"sub_categories":[],"readme":"# Pusher Channels Swift Client (also works with Objective-C)\n\n![Build Status](https://app.bitrise.io/app/3c6dac112b98e7fe.svg?token=n0z-aWua_Bc35kUGu4qpYg)\n[![codecov](https://codecov.io/gh/pusher/pusher-websocket-swift/branch/master/graph/badge.svg)](https://codecov.io/gh/pusher/pusher-websocket-swift)\n[![Latest Release](https://img.shields.io/github/v/release/pusher/pusher-websocket-swift)](https://github.com/pusher/pusher-websocket-swift/releases)\n[![CocoaPods](https://img.shields.io/cocoapods/v/PusherSwift)](https://img.shields.io/cocoapods/v/PusherSwift)\n[![API Docs](https://img.shields.io/badge/Docs-here!-lightgrey)](https://pusher.github.io/pusher-websocket-swift/)\n[![Supported Platforms](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Fpusher%2Fpusher-websocket-swift%2Fbadge%3Ftype%3Dplatforms)](https://swiftpackageindex.com/pusher/pusher-websocket-swift)\n[![Swift Versions](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Fpusher%2Fpusher-websocket-swift%2Fbadge%3Ftype%3Dswift-versions)](https://swiftpackageindex.com/pusher/pusher-websocket-swift)\n[![Twitter](https://img.shields.io/badge/twitter-@Pusher-blue.svg?style=flat)](http://twitter.com/Pusher)\n[![GitHub license](https://img.shields.io/badge/license-MIT-lightgrey.svg)](https://raw.githubusercontent.com/pusher/pusher-websocket-swift/master/LICENSE.md)\n\nThis is the [Pusher Channels](https://pusher.com/channels) websocket client, PusherSwift, which supports iOS, macOS (OS X) and tvOS. It works with Swift and Objective-C.\n\nFor tutorials and more in-depth information about Pusher Channels, visit our [official docs](https://pusher.com/docs/channels).\n\n## Supported platforms\n- Swift 5.0 and above\n- Xcode 12.0 and above\n- Can be used with Objective-C\n\n### Deployment targets\n- iOS 13.0 and above\n- macOS (OS X) 10.15 and above\n- tvOS 13.0 and above\n\n### Legacy OS support\n\nIf you need support for older versions of iOS, macOS or tvOS, please use the latest v8.x release of the SDK.\n\n## I just want to copy and paste some code to get me started\n\nWhat else would you want? Head over to one of our example apps:\n\n- For iOS with Swift, see [ViewController.swift](https://github.com/pusher/pusher-websocket-swift/blob/master/iOS%20Example%20Swift/iOS%20Example%20Swift/ViewController.swift)\n- For iOS with Objective-C, see [ViewController.m](https://github.com/pusher/pusher-websocket-swift/blob/master/iOS%20Example%20Obj-C/iOS%20Example%20Obj-C/ViewController.m)\n\n## Table of Contents\n\n- [Installation](#installation)\n  - [CocoaPods](#cocoapods)\n  - [Carthage](#carthage)\n  - [Swift Package Manager](#swift-package-manager)\n- [Configuration](#configuration)\n- [Connection](#connection)\n  - [Connection delegate](#connection-delegate)\n  - [Reconnection](#reconnection)\n- [Subscribing to channels](#subscribing)\n  - [Public channels](#public-channels)\n  - [Private channels](#private-channels)\n  - [Private encrypted channels](#private-encrypted-channels)\n  - [Presence channels](#presence-channels)\n- [Binding to events](#binding-to-events)\n  - [Per-channel](#per-channel-events)\n  - [Globally](#global-events)\n  - [Callback parameters](#callback-parameters)\n  - [Parsing event data](#parsing-event-data)\n  - [Receiving errors](#receiving-errors)\n- [Triggering events](#triggering-events)\n- [Testing](#testing)\n- [Extensions](#extensions)\n- [Communication](#communication)\n- [Credits](#credits)\n- [License](#license)\n\n## Installation\n\n### CocoaPods\n\n[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects and is our recommended method of installing PusherSwift and its dependencies.\n\nIf you don't already have the Cocoapods gem installed, run the following command:\n\n```bash\n$ gem install cocoapods\n```\n\nTo integrate PusherSwift into your Xcode project using CocoaPods, specify it in your `Podfile`:\n\n```ruby\nsource 'https://github.com/CocoaPods/Specs.git'\nplatform :ios, '10.0'\nuse_frameworks!\n\npod 'PusherSwift', '~\u003e 10.1.9'\n```\n\nThen, run the following command:\n\n```bash\n$ pod install\n```\n\nIf you find that you're not having the most recent version installed when you run `pod install` then try running:\n\n```bash\n$ pod cache clean\n$ pod repo update PusherSwift\n$ pod install\n```\n\nAlso 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.\n\n### Carthage\n\n[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that automates the process of adding frameworks to your Cocoa application.\n\nYou can install Carthage with [Homebrew](http://brew.sh/) using the following command:\n\n```bash\n$ brew update\n$ brew install carthage\n```\n\nTo integrate PusherSwift into your Xcode project using Carthage, specify it in your `Cartfile`:\n\n```ogdl\ngithub \"pusher/pusher-websocket-swift\"\n```\n\nCarthage 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`\n\n#### Xcode 12 considerations\n\nThere 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.\n\nIt is strongly recommended that you integrate PusherSwift using the `--use-xcframeworks` flag, running Carthage `0.37.0` or above. There are [full instructions](https://github.com/Carthage/Carthage#building-platform-independent-xcframeworks-xcode-12-and-above) for this (as well as instructions for [migrating to XCFrameworks](https://github.com/Carthage/Carthage#migrating-a-project-from-framework-bundles-to-xcframeworks) if you are already integrating using Carthage).\n\nAlternatively, if you are building using an Intel Mac and do not want to migrate to build Carthage dependencies using XCFrameworks there is [a workaround](https://github.com/Carthage/Carthage/blob/master/Documentation/Xcode12Workaround.md) to build successfully. You can find an example of this workaround, which is used for running the 'Consumption-Tests' [here](Consumption-Tests/Shared/carthage.sh).\n\n### Swift Package Manager\n\nTo integrate PusherSwift into your project using [Swift Package Manager](https://swift.org/package-manager/), you can add the library as a dependency in Xcode – see the [docs](https://developer.apple.com/documentation/xcode/adding_package_dependencies_to_your_app). The package repository URL is:\n\n```bash\nhttps://github.com/pusher/pusher-websocket-swift.git\n```\n\nAlternatively, you can add PusherSwift as a dependency in your `Package.swift` file. For example:\n\n```swift\n// swift-tools-version:5.1\nimport PackageDescription\n\nlet package = Package(\n    name: \"YourPackage\",\n    products: [\n        .library(\n            name: \"YourPackage\",\n            targets: [\"YourPackage\"]),\n    ],\n    dependencies: [\n        .package(url: \"https://github.com/pusher/pusher-websocket-swift.git\", from: \"10.1.9\"),\n    ],\n    targets: [\n        .target(\n            name: \"YourPackage\",\n            dependencies: [\"PusherSwift\"]),\n    ]\n)\n```\n\nYou will then need to include an `import PusherSwift` statement in any source files where you wish to use the SDK.\n\n## Configuration\n\nThere are a number of configuration parameters which can be set for the Pusher client. For Swift usage they are:\n\n- `authMethod (AuthMethod)` - the method you would like the client to use to authenticate subscription requests to channels requiring authentication (see below for more details)\n- `useTLS (Bool)` - whether or not you'd like to use TLS encrypted transport or not, default is `true`\n- `autoReconnect (Bool)` - set whether or not you'd like the library to try and automatically reconnect upon disconnection (where possible). See [Reconnection](#reconnection) for more info\n- `host (PusherHost)` - set a custom value for the host you'd like to connect to, e.g. `PusherHost.host(\"ws-test.pusher.com\")`\n- `port (Int)` - set a custom value for the port that you'd like to connect to\n- `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.\n\n\u003cdetails\u003e\u003csummary\u003eView legacy configuration options\u003c/summary\u003e\n\n- `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)\n\n\u003c/details\u003e\n\nThe `authMethod` parameter must be of the type `AuthMethod`. This is an enum defined as:\n\n```swift\npublic enum AuthMethod {\n    case endpoint(authEndpoint: String)\n    case authRequestBuilder(authRequestBuilder: AuthRequestBuilderProtocol)\n    case inline(secret: String)\n    case authorizer(authorizer: Authorizer)\n    case noMethod\n}\n```\n\n- `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\n- `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\n- `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)\n- `authorizer(authorizer: Authorizer)` - you specify an object that conforms to the `Authorizer` protocol which must be able to provide the appropriate auth information\n- `noMethod` - if you are only using public channels then you do not need to set an `authMethod` (this is the default value)\n\nThis is the `AuthRequestBuilderProtocol` definition:\n\n```swift\npublic protocol AuthRequestBuilderProtocol {\n    func requestFor(socketID: String, channelName: String) -\u003e URLRequest?\n}\n```\n\nThis is the `Authorizer` protocol definition:\n\n```swift\npublic protocol Authorizer {\n    func fetchAuthValue(socketID: String, channelName: String, completionHandler: (PusherAuth?) -\u003e ())\n}\n```\n\nwhere `PusherAuth` is defined as:\n\n```swift\npublic class PusherAuth: NSObject {\n    public let auth: String\n    public let channelData: String?\n    public let sharedSecret: String?\n\n    public init(auth: String, channelData: String? = nil, sharedSecret: String? = nil) {\n        self.auth = auth\n        self.channelData = channelData\n        self.sharedSecret = sharedSecret\n    }\n}\n```\n\nProvided the authorization process succeeds you need to then call the supplied `completionHandler` with a `PusherAuth` object so that the subscription process can complete.\n\nIf for whatever reason your authorization process fails then you just need to call the `completionHandler` with `nil` as the only parameter.\n\nNote that if you want to specify the cluster to which you want to connect then you use the `host` property as follows:\n\n#### Swift\n\n```swift\nlet options = PusherClientOptions(\n    host: .cluster(\"eu\")\n)\n```\n\n#### Objective-C\n\n```objc\nOCAuthMethod *authMethod = [[OCAuthMethod alloc] initWithAuthEndpoint:@\"https://your.authendpoint/pusher/auth\"];\nOCPusherHost *host = [[OCPusherHost alloc] initWithCluster:@\"eu\"];\nPusherClientOptions *options = [[PusherClientOptions alloc]\n                                initWithOcAuthMethod:authMethod\n                                autoReconnect:YES\n                                ocHost:host\n                                port:nil\n                                useTLS:YES\n                                activityTimeout:nil];\n```\n\nAll 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:\n\n#### Swift\n\n```swift\nlet options = PusherClientOptions(\n    authMethod: .endpoint(authEndpoint: \"http://localhost:9292/pusher/auth\")\n)\n\nlet pusher = Pusher(key: \"APP_KEY\", options: options)\n```\n\n#### Objective-C\n\n```objc\nOCAuthMethod *authMethod = [[OCAuthMethod alloc] initWithAuthEndpoint:@\"https://your.authendpoint/pusher/auth\"];\nOCPusherHost *host = [[OCPusherHost alloc] initWithCluster:@\"eu\"];\nPusherClientOptions *options = [[PusherClientOptions alloc]\n                                initWithOcAuthMethod:authMethod\n                                autoReconnect:YES\n                                ocHost:host\n                                port:nil\n                                useTLS:YES\n                                activityTimeout:nil];\npusher = [[Pusher alloc] initWithAppKey:@\"YOUR_APP_KEY\" options:options];\n```\n\nAs 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.\n\n```swift\npublic init(authEndpoint: String)\n\npublic init(authRequestBuilder: AuthRequestBuilderProtocol)\n\npublic init(secret: String)\n\npublic init()\n```\n\n```objc\nOCAuthMethod *authMethod = [[OCAuthMethod alloc] initWithSecret:@\"YOUR_APP_SECRET\"];\nPusherClientOptions *options = [[PusherClientOptions alloc] initWithAuthMethod:authMethod];\n```\n\nThe case is similar for `OCPusherHost`. You have the following functions available:\n\n```objc\npublic init(host: String)\n\npublic init(cluster: String)\n```\n\n```objc\n[[OCPusherHost alloc] initWithCluster:@\"YOUR_CLUSTER_SHORTCODE\"];\n```\n\nAuthenticated channel example:\n\n#### Swift\n\n```swift\nclass AuthRequestBuilder: AuthRequestBuilderProtocol {\n    func requestFor(socketID: String, channelName: String) -\u003e URLRequest? {\n        var request = URLRequest(url: URL(string: \"http://localhost:9292/builder\")!)\n        request.httpMethod = \"POST\"\n        request.httpBody = \"socket_id=\\(socketID)\u0026channel_name=\\(channel.name)\".data(using: String.Encoding.utf8)\n        request.addValue(\"myToken\", forHTTPHeaderField: \"Authorization\")\n        return request\n    }\n}\n\nlet options = PusherClientOptions(\n    authMethod: AuthMethod.authRequestBuilder(authRequestBuilder: AuthRequestBuilder())\n)\nlet pusher = Pusher(\n  key: \"APP_KEY\",\n  options: options\n)\n```\n\n#### Objective-C\n\n```objc\n@interface AuthRequestBuilder : NSObject \u003cAuthRequestBuilderProtocol\u003e\n\n- (NSURLRequest *)requestForSocketID:(NSString *)socketID channelName:(NSString *)channelName;\n\n@end\n\n@implementation AuthRequestBuilder\n\n- (NSURLRequest *)requestForSocketID:(NSString *)socketID channelName:(NSString *)channelName {\n    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[[NSURL alloc] initWithString:@\"http://localhost:9292/pusher/auth\"]];\n    NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL: [[NSURL alloc] initWithString:@\"http://localhost:9292/pusher/auth\"]];\n\n    NSString *dataStr = [NSString stringWithFormat: @\"socket_id=%@\u0026channel_name=%@\", socketID, channelName];\n    NSData *data = [dataStr dataUsingEncoding:NSUTF8StringEncoding];\n    mutableRequest.HTTPBody = data;\n    mutableRequest.HTTPMethod = @\"POST\";\n    [mutableRequest addValue:@\"myToken\" forHTTPHeaderField:@\"Authorization\"];\n\n    request = [mutableRequest copy];\n\n    return request;\n}\n\n@end\n\nOCAuthMethod *authMethod = [[OCAuthMethod alloc] initWithAuthRequestBuilder:[[AuthRequestBuilder alloc] init]];\nPusherClientOptions *options = [[PusherClientOptions alloc] initWithAuthMethod:authMethod];\n```\n\nWhere `\"Authorization\"` and `\"myToken\"` are the field and value your server is expecting in the headers of the request.\n\n## Connection\n\nA Websocket connection is established by providing your API key to the constructor function:\n\n#### Swift\n\n```swift\nlet pusher = Pusher(key: \"APP_KEY\")\npusher.connect()\n```\n\n#### Objective-C\n\n```objc\nPusher *pusher = [[Pusher alloc] initWithAppKey:@\"YOUR_APP_KEY\"];\n[pusher connect];\n```\n\nThis returns a client object which can then be used to subscribe to channels and then calling `connect()` triggers the connection process to start.\n\n**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.\n\nYou can also set a `userDataFetcher` on the connection object.\n\n- `userDataFetcher (() -\u003e PusherPresenceChannelMember)` - if you are subscribing to an authenticated channel and wish to provide a function to return user data\n\nYou set it like this:\n\n#### Swift\n\n```swift\nlet pusher = Pusher(key: \"APP_KEY\")\n\npusher.connection.userDataFetcher = { () -\u003e PusherPresenceChannelMember in\n    return PusherPresenceChannelMember(userId: \"123\", userInfo: [\"twitter\": \"hamchapman\"])\n}\n```\n\n#### Objective-C\n\n```objc\nPusher *pusher = [[Pusher alloc] initWithAppKey:@\"YOUR_APP_KEY\"];\n\npusher.connection.userDataFetcher = ^PusherPresenceChannelMember* () {\n    NSString *uuid = [[NSUUID UUID] UUIDString];\n    return [[PusherPresenceChannelMember alloc] initWithUserId:uuid userInfo:nil];\n};\n```\n\n### Connection delegate\n\nThere 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:\n\n```swift\n@objc optional func changedConnectionState(from old: ConnectionState, to new: ConnectionState)\n@objc optional func subscribedToChannel(name: String)\n@objc optional func failedToSubscribeToChannel(name: String, response: URLResponse?, data: String?, error: NSError?)\n@objc optional func debugLog(message: String)\n@objc(receivedError:) optional func receivedError(error: PusherError)\n@objc optional func failedToDecryptEvent(eventName: String, channelName: String, data: String?)\n```\n\nThe names of the functions largely give away what their purpose is but just for completeness:\n\n- `changedConnectionState` - use this if you want to use connection state changes to perform different actions / UI updates\n- `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\n- `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\n- `debugLog` - use this if you want to log Pusher-related events, e.g. the underlying websocket receiving a message\n- `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](https://pusher.com/docs/channels/library_auth_reference/pusher-websockets-protocol#error-codes).\n- `failedToDecryptEvent` - only used with private encrypted channels - use this if you want to be notified if any messages fail to decrypt.\n\nSetting up a delegate looks like this:\n\n#### Swift\n\n```swift\nclass ViewController: UIViewController, PusherDelegate {\n\n    override func viewDidLoad() {\n        super.viewDidLoad()\n        let pusher = Pusher(key: \"APP_KEY\")\n        pusher.connection.delegate = self\n        // ...\n    }\n}\n```\n\n#### Objective-C\n\n```objc\n@implementation ViewController\n\n- (void)viewDidLoad {\n    [super viewDidLoad];\n\n    self.client = [[Pusher alloc] initWithAppKey:@\"YOUR_APP_KEY\"];\n\n    self.client.connection.delegate = self;\n    // ...\n}\n```\n\nHere are examples of setting up a class with functions for each of the optional protocol functions:\n\n#### Swift\n\n```swift\nclass DummyDelegate: PusherDelegate {\n    func changedConnectionState(from old: ConnectionState, to new: ConnectionState) {\n        // ...\n    }\n\n    func debugLog(message: String) {\n        // ...\n    }\n\n    func subscribedToChannel(name: String) {\n        // ...\n    }\n\n    func failedToSubscribeToChannel(name: String, response: URLResponse?, data: String?, error: NSError?) {\n        // ...\n    }\n\n    func receivedError(error: PusherError) {\n        let message = error.message\n        if let code = error.code {\n            // ...\n        }\n    }\n\n    func failedToDecryptEvent(eventName: String, channelName: String, data: String?) {\n      // ...\n    }\n\n}\n```\n\n#### Objective-C\n\n```objc\n@interface DummyDelegate : NSObject \u003cPusherDelegate\u003e\n\n- (void)changedConnectionState:(enum ConnectionState)old to:(enum ConnectionState)new_\n- (void)debugLogWithMessage:(NSString *)message\n- (void)subscribedToChannelWithName:(NSString *)name\n- (void)failedToSubscribeToChannelWithName:(NSString *)name response:(NSURLResponse *)response data:(NSString *)data error:(NSError *)error\n- (void)receivedError:(PusherError *)error\n- (void)failedToDecryptEventWithEventName:(NSString *)eventName channelName:(NSString *)channelName data:(NSString *)data\n\n@end\n\n@implementation DummyDelegate\n\n- (void)changedConnectionState:(enum ConnectionState)old to:(enum ConnectionState)new_ {\n    // ...\n}\n\n- (void)debugLogWithMessage:(NSString *)message {\n    // ...\n}\n\n- (void)subscribedToChannelWithName:(NSString *)name {\n    // ...\n}\n\n- (void)failedToSubscribeToChannelWithName:(NSString *)name response:(NSURLResponse *)response data:(NSString *)data error:(NSError *)error {\n    // ...\n}\n\n- (void)receivedError:(PusherError *)error {\n    NSNumber *code = error.codeOC;\n    NSString *message = error.message;\n    // ...\n}\n\n- (void)failedToDecryptEventWithEventName:(NSString *)eventName channelName:(NSString *)channelName data:(NSString *)data {\n  // ...\n}\n\n@end\n```\n\nThe different states that the connection can be in are (Objective-C integer enum cases in brackets):\n\n- `connecting (0)` - the connection is about to attempt to be made\n- `connected (1)` - the connection has been successfully made\n- `disconnecting (2)` - the connection has been instructed to disconnect and it is just about to do so\n- `disconnected (3)` - the connection has disconnected and no attempt will be made to reconnect automatically\n- `reconnecting (4)` - an attempt is going to be made to try and re-establish the connection\n\nThere is a `stringValue()` function that you can call on `ConnectionState` objects in order to get a `String` representation of the state, for example `\"connecting\"`.\n\n### Reconnection\n\nThere are three main ways in which a disconnection can occur:\n\n- The client explicitly calls disconnect and a close frame is sent over the websocket connection\n- The client experiences some form of network degradation which leads to a heartbeat (ping/pong) message being missed and thus the client disconnects\n- 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\n\nIn the case of the first type of disconnection the library will (as you'd hope) not attempt a reconnection.\n\nThe library uses [NWWebSocket](https://github.com/pusher/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.\n\nIf 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.\n\nAll 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\nN.B: If the Pusher servers close the websocket with a [Channels Protocol closure code](https://pusher.com/docs/channels/library_auth_reference/pusher-websockets-protocol#connection-closure), then the `autoReconnect` option is ignored, and the reconnection strategy is determined by the specific closure code that was received.\n\nThere are a couple of properties on the connection (`PusherConnection`) that you can set that affect how the reconnection behavior works. These are:\n\n- `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`\n- `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\n\nNote that the number of reconnect attempts gets reset to 0 as soon as a successful connection is made.\n\n## Subscribing\n\n### Public channels\n\nThe default method for subscribing to a channel involves invoking the `subscribe` method of your client object:\n\n#### Swift\n\n```swift\nlet myChannel = pusher.subscribe(\"my-channel\")\n```\n\n#### Objective-C\n\n```objc\nPusherChannel *myChannel = [pusher subscribeWithChannelName:@\"my-channel\"];\n```\n\nThis returns PusherChannel object, which events can be bound to.\n\nFor 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.\n\n```swift\nlet onSubscriptionCountChanged = { (count: Int) in\n    print(\"\\(count) subscriptions\")\n}\n\nlet channel = pusher.subscribe(\n    channelName: \"my-channel\",\n    onSubscriptionCountChanged: onSubscriptionCountChanged\n)\n```\n\n### Private channels\n\nPrivate 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:\n\n#### Swift\n\n```swift\nlet myPrivateChannel = pusher.subscribe(\"private-my-channel\")\n```\n\n#### Objective-C\n\n```objc\nPusherChannel *myPrivateChannel = [pusher subscribeWithChannelName:@\"private-my-channel\"];\n```\n\nSubscribing to private channels involves the client being authenticated. See the [Configuration](#configuration) section for the authenticated channel example for more information.\n\n### Private encrypted channels\n\nSimilar to Private channels, you can also subscribe to a [private encrypted channel](https://pusher.com/docs/channels/using_channels/encrypted-channels). 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.\n\nLike with private channels, you must provide an authentication endpoint. That endpoint must be using a [server client that supports end-to-end encryption](https://pusher.com/docs/channels/using_channels/encrypted-channels#server). There is a [demonstration endpoint to look at using nodejs](https://github.com/pusher/pusher-channels-auth-example#using-e2e-encryption).\n\nThe 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.\n\nBecause of the requirement to reload the shared secret on demand, you can only use the following [auth methods](#configuration): `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.\n\n#### Limitations\n\n* Is not safe for use in extensions\n* Client events are not supported on encrypted channels\n\n#### Swift\n\n```swift\nlet privateEncryptedChannel = pusher.subscribe(channelName: \"private-encrypted-my-channel\")\n```\n\n#### Objective-C\n\n```objc\nPusherChannel *privateEncryptedChannel = [pusher subscribeWithChannelName:@\"private-encrypted-my-channel\"];\n```\n\nThere is also an optional callback in the connection delegate when you can listen for\nany failed decryption events:\n\n```swift\noptional func failedToDecryptEvent(eventName: String, channelName: String, data: String?)\n```\n\n### Presence channels\n\nPresence channels are channels whose names are prefixed by `presence-`.\n\nThe 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`.\n\n#### Swift\n\n```swift\nlet myPresenceChannel = pusher.subscribeToPresenceChannel(channelName: \"presence-my-channel\")\n```\n\n#### Objective-C\n\n```objc\nPusherPresenceChannel *myPresenceChannel = [pusher subscribeToPresenceChannelWithChannelName:@\"presence-my-channel\"];\n```\n\nAs 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`.\n\n#### Swift\n\n```swift\nlet myPresenceChannel = pusher.subscribe(\"presence-my-channel\")\n```\n\n#### Objective-C\n\n```objc\nPusherChannel *myPresenceChannel = [pusher subscribeWithChannelName:@\"presence-my-channel\"];\n```\n\nYou 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`.\n\n#### Swift\n\n```swift\nlet onMemberChange = { (member: PusherPresenceChannelMember) in\n    print(member)\n}\n\nlet chan = pusher.subscribeToPresenceChannel(\"presence-channel\", onMemberAdded: onMemberChange, onMemberRemoved: onMemberChange)\n```\n\n#### Objective-C\n\n```objc\nvoid (^onMemberChange)(PusherPresenceChannelMember*) = ^void (PusherPresenceChannelMember *member) {\n    NSLog(@\"%@\", member);\n};\n\nPusherChannel *myPresenceChannel = [pusher subscribeWithChannelName:@\"presence-my-channel\" onMemberAdded:onMemberChange onMemberRemoved:onMemberChange];\n```\n\n**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.\n\nThe 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:\n\n#### Swift\n\n```swift\nlet pusher = Pusher(key: \"YOUR_APP_KEY\")\n\nlet chan = pusher.subscribeToPresenceChannel(\"presence-channel\")\n\nchan.bind(eventName: \"pusher:subscription_succeeded\", eventCallback: { event in\n    print(\"Subscribed!\")\n    print(\"I can now access myId: \\(chan.myId)\")\n    print(\"And here are the channel members: \\(chan.members)\")\n})\n```\n\n#### Objective-C\n\n```objc\nPusher *pusher = [[Pusher alloc] initWithAppKey:@\"YOUR_APP_KEY\"];\nPusherPresenceChannel *chan = [pusher subscribeToPresenceChannelWithChannelName:@\"presence-channel\"];\n\n[chan bindWithEventName:@\"pusher:subscription_succeeded\" eventCallback: ^void (PusherEvent *event) {\n    NSLog(@\"Subscribed!\");\n    NSLog(@\"I can now access myId: %@\", chan.myId);\n    NSLog(@\"And here are my channel members: %@\", chan.members);\n}];\n```\n\nYou can also be notified of a successful subscription by using the `subscriptionDidSucceed` delegate method that is part of the `PusherDelegate` protocol.\n\nHere is an example of using the delegate:\n\n#### Swift\n\n```swift\nclass DummyDelegate: PusherDelegate {\n    func subscribedToChannel(name: String) {\n        if channelName == \"presence-channel\" {\n            if let presChan = pusher.connection.channels.findPresence(channelName) {\n                // in here you can now have access to the channel's members and myId properties\n                print(presChan.members)\n                print(presChan.myId)\n            }\n        }\n    }\n}\n\nlet pusher = Pusher(key: \"YOUR_APP_KEY\")\npusher.connection.delegate = DummyDelegate()\nlet chan = pusher.subscribeToPresenceChannel(\"presence-channel\")\n```\n\n#### Objective-C\n\n```objc\n@implementation DummyDelegate\n\n- (void)subscribedToChannelWithName:(NSString *)name {\n    if ([channelName isEqual: @\"presence-channel\"]) {\n        PusherPresenceChannel *presChan = [self.client.connection.channels findPresenceWithName:@\"presence-channel\"];\n        NSLog(@\"%@\", [presChan members]);\n        NSLog(@\"%@\", [presChan myId]);\n    }\n}\n\n@implementation ViewController\n\n- (void)viewDidLoad {\n    // ...\n\n    Pusher *pusher = [[Pusher alloc] initWithAppKey:@\"YOUR_APP_KEY\"];\n    pusher.connection.delegate = [[DummyDelegate alloc] init];\n    PusherChannel *chan = [pusher subscribeToPresenceChannelWithChannelName:@\"presence-channel\"];\n```\n\nNote 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.\n\nWe 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.\n\n### Subscribing with self-provided auth values\n\nIt 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:\n\n#### Swift\n\n```swift\nlet pusherAuth = PusherAuth(auth: yourAuthString, channelData: yourOptionalChannelDataString)\nlet chan = self.pusher.subscribe(channelName, auth: pusherAuth)\n```\n\nThis 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.\n\nThese `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.\n\nKeep 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.\n\n## Binding to events\n\nEvents 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.\n\n### Per-channel events\n\nThese are bound to a specific channel, and mean that you can reuse event names in different parts of your client application.\n\n#### Swift\n\n```swift\nlet pusher = Pusher(key: \"YOUR_APP_KEY\")\nlet myChannel = pusher.subscribe(\"my-channel\")\n\nmyChannel.bind(eventName: \"new-price\", eventCallback: { (event: PusherEvent) -\u003e Void in\n    if let data: String = event.data {\n        // `data` is a string that you can parse if necessary.\n    }\n})\n```\n\nThe callback is passed a `PusherEvent`  (see [docs](#pusherevent)).\n\n\u003cdetails\u003e\u003csummary\u003eView legacy approach\u003c/summary\u003e\n\n```swift\nlet pusher = Pusher(key: \"YOUR_APP_KEY\")\nlet myChannel = pusher.subscribe(\"my-channel\")\n\nmyChannel.bind(eventName: \"new-price\", callback: { (data: Any?) -\u003e Void in\n    if let data = data as? [String : AnyObject] {\n        if let price = data[\"price\"] as? String, company = data[\"company\"] as? String {\n            print(\"\\(company) is now priced at \\(price)\")\n        }\n    }\n})\n```\n\u003c/details\u003e\n\n#### Objective-C\n\n```objc\nPusher *pusher = [[Pusher alloc] initWithAppKey:@\"YOUR_APP_KEY\"];\nPusherChannel *chan = [pusher subscribeWithChannelName:@\"my-channel\"];\n\n[chan bindWithEventName:@\"new-price\" eventCallback:^void (PusherEvent *event) {\n    NSString *data = event.data;\n    // `data` is a string that you can parse if necessary.\n}];\n```\n\u003cdetails\u003e\u003csummary\u003eView legacy approach\u003c/summary\u003e\n\n```objc\nPusher *pusher = [[Pusher alloc] initWithAppKey:@\"YOUR_APP_KEY\"];\nPusherChannel *chan = [pusher subscribeWithChannelName:@\"my-channel\"];\n\n[chan bindWithEventName:@\"new-price\" callback:^void (NSDictionary *data) {\n    NSString *price = data[@\"price\"];\n    NSString *company = data[@\"company\"];\n\n    NSLog(@\"%@ is now priced at %@\", company, price);\n}];\n```\n\u003c/details\u003e\n\n### Global events\n\nYou can attach behavior to these events regardless of the channel the event is broadcast to.\n\n#### Swift\n\n```swift\nlet pusher = Pusher(key: \"YOUR_APP_KEY\")\npusher.subscribe(\"my-channel\")\n\npusher.bind(eventCallback: { (event: PusherEvent) -\u003e Void in\n    if let data: String = event.data {\n        // `data` is a string that you can parse if necessary.\n    }\n})\n```\nThe callback is passed a `PusherEvent`  (see [docs](#pusherevent)).\n\n\u003cdetails\u003e\u003csummary\u003eView legacy approach\u003c/summary\u003e\n\n```swift\nlet pusher = Pusher(key: \"YOUR_APP_KEY\")\npusher.subscribe(\"my-channel\")\n\npusher.bind(callback: { (event: Any?) -\u003e Void in\n    if let data = event[\"data\"] as? [String : AnyObject] {\n        if let commenter = data[\"commenter\"] as? String, message = data[\"message\"] as? String {\n            print(\"\\(commenter) wrote \\(message)\")\n        }\n    }\n})\n```\n\u003c/details\u003e\n\n#### Objective-C\n\n```objc\nPusher *pusher = [[Pusher alloc] initWithAppKey:@\"YOUR_APP_KEY\"];\nPusherChannel *chan = [pusher subscribeWithChannelName:@\"my-channel\"];\n\n[pusher bindWithEventCallback: ^void (PusherEvent *event) {\n    // `data` is a string that you can parse if necessary.\n    NSString *data = event.data;\n}];\n```\n\u003cdetails\u003e\u003csummary\u003eView legacy approach\u003c/summary\u003e\n\n```objc\nPusher *pusher = [[Pusher alloc] initWithAppKey:@\"YOUR_APP_KEY\"];\nPusherChannel *chan = [pusher subscribeWithChannelName:@\"my-channel\"];\n\n[pusher bind: ^void (NSDictionary *event) {\n    NSDictionary *data = event[@\"data\"];\n    NSString *commenter = data[@\"commenter\"];\n    NSString *message = data[@\"message\"];\n\n    NSLog(@\"%@ wrote %@\", commenter, message);\n}];\n```\n\u003c/details\u003e\n\n### Callback parameters\n\n#### PusherEvent\n\nThe callbacks you bind receive a `PusherEvent`:\n\n|  Property            | Type           | Description  |\n| ------------------ |--------------| ------------\n| `eventName`       | `String`      | The name of the event. |\n| `channelName`   | `String?`    | The name of the channel that the event was triggered on. |\n| `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](#parsing-event-data). |\n| `userId`            | `String?`     | The ID of the user who triggered the event. This is only available for client events triggered on presence channels. |\n\n| Function            | Parameters                                                    |  Return Type           | Description                                                                                                                                                                                                     |\n| -----------------  |---------------------------------------------------| -----------------------| ----------------------------------------------------------------------------------------------------------------------------------------------------------|\n| `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. |\n\n### Parsing event data\n\nThe `data` property of  [`PusherEvent`](#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`](https://developer.apple.com/swift/blog/?id=37), 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](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types).\n\nFor 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:\n\n```swift\nstruct PriceUpdate: Codable {\n    public let company: String,\n    public let price: Int,\n}\n\nlet pusher = Pusher(key: \"YOUR_APP_KEY\")\nlet myChannel = pusher.subscribe(\"my-channel\")\nlet decoder = JSONDecoder()\n\nmyChannel.bind(eventName: \"price-update\", eventCallback: { (event: PusherEvent) -\u003e Void in\n    guard let json: String = event.data,\n        let jsonData: Data = json.data(using: .utf8)\n    else{\n        print(\"Could not convert JSON string to data\")\n        return\n    }\n\n    let decoded = try? decoder.decode(PriceUpdate.self, from: jsonData)\n    guard let priceUpdate = decoded else {\n        print(\"Could not decode price update\")\n        return\n    }\n\n    print(\"\\(priceUpdate.company) is now priced at \\(priceUpdate.price)\")\n})\n\n```\n\nAlternatively, you could use [`JSONSerialization`](https://developer.apple.com/documentation/foundation/jsonserialization) to decode the JSON into Swift data types:\n\n#### Swift\n\n```swift\nlet pusher = Pusher(key: \"YOUR_APP_KEY\")\nlet myChannel = pusher.subscribe(\"my-channel\")\n\nmyChannel.bind(eventName: \"price-update\", eventCallback: { (event: PusherEvent) -\u003e Void in\n    guard let json: String = event.data,\n        let jsonData: Data = json.data(using: .utf8)\n    else{\n        print(\"Could not convert JSON string to data\")\n        return\n    }\n\n    let decoded = try? JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any]\n    guard let priceUpdate = decoded else {\n        print(\"Could not decode price update\")\n        return\n    }\n\n    if let company = priceUpdate[\"company\"] as? String, let price = priceUpdate[\"price\"] as? String {\n        print(\"\\(company) is now priced at \\(price)\")\n    }\n})\n```\n#### Objective-C\n\n```objc\nPusher *pusher = [[Pusher alloc] initWithAppKey:@\"YOUR_APP_KEY\"];\nPusherChannel *chan = [pusher subscribeWithChannelName:@\"my-channel\"];\n\n[chan bindWithEventName:@\"price-update\" eventCallback:^void (PusherEvent *event) {\n    NSString *dataString = event.data;\n    NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];\n\n    NSError *error;\n    NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:\u0026error];\n\n    NSString *price = jsonObject[@\"price\"];\n    NSString *company = jsonObject[@\"company\"];\n\n    NSLog(@\"%@ is now priced at %@\", company, price);\n}];\n```\n\n### Receiving errors\n\nErrors received from Pusher Channels can be accessed via the [connection delegate](#connection-delegate). This was previously done by binding callbacks.\n\n\u003cdetails\u003e\u003csummary\u003eView legacy approach\u003c/summary\u003e\n\nErrors 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.\n\n#### Swift\n\n```swift\npusher.bind({ (message: Any?) in\n    if let message = message as? [String: AnyObject], eventName = message[\"event\"] as? String where eventName == \"pusher:error\" {\n        if let data = message[\"data\"] as? [String: AnyObject], errorMessage = data[\"message\"] as? String {\n            print(\"Error message: \\(errorMessage)\")\n        }\n    }\n})\n```\n\n#### Objective-C\n\n```objc\n[pusher bind:^void (NSDictionary *data) {\n    NSString *eventName = data[@\"event\"];\n\n    if ([eventName isEqualToString:@\"pusher:error\"]) {\n        NSString *errorMessage = data[@\"data\"][@\"message\"];\n        NSLog(@\"Error message: %@\", errorMessage);\n    }\n}];\n```\n\nThe sort of errors you might get are:\n\n```bash\n# if attempting to subscribe to an already subscribed-to channel\n\n\"{\\\"event\\\":\\\"pusher:error\\\",\\\"data\\\":{\\\"code\\\":null,\\\"message\\\":\\\"Existing subscription to channel presence-channel\\\"}}\"\n\n# if the auth signature generated by your auth mechanism is invalid\n\n\"{\\\"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\\\"}}\"\n```\n\nYou can see that the general form they take is:\n\n```bash\n{\n  \"event\": \"pusher:error\",\n  \"data\": {\n    \"code\": null,\n    \"message\": \"Error message here\"\n  }\n}\n```\n\n\u003c/details\u003e\n\n### Unbind event handlers\n\nYou can remove previously-bound handlers from an object by using the `unbind` function. For example,\n\n#### Swift\n\n```swift\nlet pusher = Pusher(key: \"YOUR_APP_KEY\")\nlet myChannel = pusher.subscribe(\"my-channel\")\n\nlet eventHandlerId = myChannel.bind(eventName: \"new-price\", eventCallback: { (event: PusherEvent) -\u003e Void in\n  //...\n})\n\nmyChannel.unbind(eventName: \"new-price\", callbackId: eventHandlerId)\n```\n\n#### Objective-C\n\n```objc\nPusher *pusher = [[Pusher alloc] initWithAppKey:@\"YOUR_APP_KEY\"];\nPusherChannel *chan = [pusher subscribeWithChannelName:@\"my-channel\"];\n\nNSString *callbackId = [chan bindWithEventName:@\"new-price\" eventCallback:^void (PusherEvent *event) {\n    //...\n}];\n\n[chan unbindWithEventName:@\"new-price\" callbackId:callbackId];\n```\n\nYou 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.\n\n## Triggering events\n\nOnce a [private](https://pusher.com/docs/channels/using_channels/private-channels) or [presence](https://pusher.com/docs/channels/using_channels/presence-channels) subscription has been authorized (see [authenticating users](https://pusher.com/docs/channels/server_api/authenticating-users)) and the subscription has succeeded, it is possible to trigger events on those channels.\n\n```swift\nchan.trigger(eventName: \"client-myEvent\", data: [\"myName\": \"Bob\"])\n```\n\nEvents triggered by clients are called [client events](https://pusher.com/docs/channels/using_channels/events#triggering-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:\n\n* Event names must have a `client-` prefix\n* Rate limits\n* You can only trigger an event when the subscription has succeeded\n\nFor full details see the [client events documentation](https://pusher.com/docs/channels/using_channels/events#triggering-client-events).\n\n## Testing\n\nThere are a set of tests for the library that can be run using the standard method (Command-U in Xcode).\n\nThe tests also get run on Github Actions, see [CI Action](https://github.com/pusher/pusher-websocket-swift/actions/workflows/ci.yml)\n\n## Extensions\n\n- [RxPusherSwift](https://github.com/jondwillis/RxPusherSwift)\n\n## Communication\n\n- If you have found a bug, please open an issue.\n- If you have a feature request, please open an issue.\n- If you want to contribute, please submit a pull request (preferably with some tests 🙂 ).\n- If you do not receive a timely response, feel free to check our [support portal](https://docs.bird.com/pusher).\n\n## Credits\n\nPusherSwift is owned and maintained by [Pusher](https://pusher.com). It was originally created by [Hamilton Chapman](https://github.com/hamchapman).\n\nIt uses code from the following repositories:\n\n- [TweetNacl](https://github.com/bitmark-inc/tweetnacl-swiftwrap)\n\nThe individual licenses for these libraries are included in the corresponding Swift files.\n\n## License\n\nPusherSwift is released under the MIT license. See [LICENSE](https://github.com/pusher/pusher-websocket-swift/blob/master/LICENSE.md) for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpusher%2Fpusher-websocket-swift","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpusher%2Fpusher-websocket-swift","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpusher%2Fpusher-websocket-swift/lists"}