PusherSwift WebSocket Client

repository·master·Indexed 43 days ago

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

A WebSocket client for Pusher Channels supporting iOS, macOS, and tvOS. Compatible with Swift 5.0+ and Objective-C, it provides tools for managing public, private, and private encrypted channels, including support for custom authentication via AuthRequestBuilderProtocol and Authorizer protocols. Available via CocoaPods, Carthage, and Swift Package Manager.

Tokens
5.8K
Snippets
20
Records
25
Agent score
55%

What's inside PusherSwift

  1. PusherSwift Supported Platforms and Requirements

    master

    PusherSwift supports iOS, macOS, and tvOS for both Swift and Objective-C development.

    Requirements:

    • Swift 5.0 and above
    • Xcode 12.0 and above

    Deployment Targets:

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

    Legacy Support: If you need to support older versions of iOS, macOS, or tvOS, use the latest v8.x release of the SDK.

  2. Understand ConnectionState values

    master

    The ConnectionState enum represents the current lifecycle stage of the websocket connection. You can use the stringValue() method on a state object to get a human-readable string (e.g., "connecting").

    Possible states:

    • connecting (0): Attempting to establish a connection.
    • connected (1): Connection successfully established.
    • disconnecting (2): Instructed to disconnect; in the process of closing.
    • disconnected (3): Connection is closed; no automatic reconnection will occur.
    • reconnecting (4): Attempting to re-establish a lost connection.
  3. Configure AuthMethod for Authenticated Channels

    master

    When subscribing to channels that require authentication, you must specify an AuthMethod. The AuthMethod enum provides several ways to handle this:

    • .endpoint(authEndpoint: String): The client performs a POST request to the specified endpoint, including the socket_id and channel_name in the request.
    • .authRequestBuilder(authRequestBuilder: AuthRequestBuilderProtocol): You provide a custom object conforming to AuthRequestBuilderProtocol to generate a URLRequest for the authentication process.
    • .inline(secret: String): Uses your app's secret to authenticate subscriptions directly within the library. Note: This is primarily for development.
    • .authorizer(authorizer: Authorizer): You provide a custom object conforming to the Authorizer protocol to provide authentication information.
    • .noMethod: The default value; use this if you are only using public channels.
    public enum AuthMethod {
        case endpoint(authEndpoint: String)
        case authRequestBuilder(authRequestBuilder: AuthRequestBuilderProtocol)
        case inline(secret: String)
        case authorizer(authorizer: Authorizer)
        case noMethod
    }
  4. Update supported toolset versions

    master

    If you need to update the minimum or latest supported versions for Xcode, Swift, or deployment targets (iOS, macOS, tvOS), you must adjust the values in the following configuration files:

    • LATEST_SUPPORTED_VERSIONS.xcconfig
    • LATEST_SUPPORTED_XCODE_VERSION
    • MINIMUM_SUPPORTED_VERSIONS.xcconfig
    • MINIMUM_SUPPORTED_XCODE_VERSION
  5. Establish a connection to Pusher

    master

    To start using Pusher, initialize a Pusher client with your application key and call connect().

    Important: You must maintain a strong reference to the Pusher instance (e.g., as a property in your AppDelegate or a long-lived Controller) to prevent it from being deallocated while the connection is active.

    let pusher = Pusher(key: "APP_KEY")
    pusher.connect()
  6. Install PusherSwift via CocoaPods

    master

    CocoaPods is the recommended method for installing PusherSwift.

    1. Ensure the CocoaPods gem is installed: gem install cocoapods.
    2. Add pod 'PusherSwift', '~> 10.1.10' to your Podfile.
    3. Run pod install in your terminal.

    If you encounter issues with versioning, try cleaning the cache and updating the repo:

    $ pod cache clean
    $ pod repo update PusherSwift
    $ pod install
    source 'https://github.com/CocoaPods/Specs.git'
    platform :ios, '10.0'
    use_frameworks!
    
    pod 'PusherSwift', '~> 10.1.10'
  7. Install PusherSwift via Carthage

    master

    To use Carthage, add the repository to your Cartfile:

    github "pusher/pusher-websocket-swift"

    After building, you must include the following framework binaries from the Carthage/Build directory in your Xcode project:

    • PusherSwift
    • NWWebSocket
    • TweetNacl

    Note for Xcode 12+ (Apple Silicon support): It is strongly recommended to use Carthage 0.37.0 or above with the --use-xcframeworks flag to ensure proper architecture support.

  8. Install PusherSwift via Swift Package Manager

    master

    You can integrate PusherSwift using the Xcode interface or by manually editing your Package.swift file.

    Package Repository URL: https://github.com/pusher/pusher-websocket-swift.git

    Manual Package.swift configuration: Add the dependency to your dependencies array and include PusherSwift in your target's dependencies. Remember to import PusherSwift in your source files.

    // 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.10"),
        ],
        targets: [
            .target(
                name: "YourPackage",
                dependencies: ["PusherSwift"]),
        ]
    )
  9. Run the Consumption Test Suite locally

    master

    The Consumption Tests verify that the core project can be integrated into various client environments (Carthage, CocoaPods, or Swift Package Manager) across different toolsets (Minimum vs. Latest). Note that these tests only verify that the code compiles; they do not execute unit tests.

    To run the full suite, execute the provided shell script from the repository root.

    sh ./Consumption-Tests/run-tests-LOCALLY.sh
  10. Configure PusherClientOptions in Objective-C

    master

    In Objective-C, configuration uses OCAuthMethod and OCPusherHost instead of the Swift enums/structs.

    Auth Methods (OCAuthMethod):

    • initWithAuthEndpoint:
    • initWithAuthRequestBuilder:
    • initWithSecret:
    • init

    Host Configuration (OCPusherHost):

    • initWithHost:
    • initWithCluster:

    Example Setup:

    ```objc
    // Using a cluster
    OCPusherHost *host = [[OCPusherHost alloc] initWithCluster:@
  11. Configure reconnection behavior

    master

    The library attempts to reconnect automatically by default (autoReconnect is true). It uses exponential backoff to handle network degradation. You can customize this behavior via the PusherConnection object:

    • reconnectAttemptsMax: The maximum number of reconnection attempts. Set to nil for infinite attempts. Default is 6.
    • maxReconnectGapInSeconds: The maximum time (in seconds) allowed between reconnection attempts.

    If you need a custom strategy, set autoReconnect to false and monitor changedConnectionState via the PusherDelegate to trigger your own logic.

    // Example: Limit to 10 attempts and cap gap at 30 seconds
    pusher.connection.reconnectAttemptsMax = 10
    pusher.connection.maxReconnectGapInSeconds = 30.0
  12. Configure PusherClientOptions in Swift

    master

    To initialize a Pusher instance, you must provide a PusherClientOptions object. This object allows you to configure connection behavior, authentication, and host settings.

    Available configuration parameters for Swift:

    • authMethod (AuthMethod): The method used to authenticate subscription requests to private/presence channels.
    • useTLS (Bool): Whether to use TLS encrypted transport (defaults to true).
    • autoReconnect (Bool): Whether the library should attempt to automatically reconnect upon disconnection.
    • host (PusherHost): A custom host value (e.g., PusherHost.cluster("eu") or PusherHost.host("ws-test.pusher.com")).
    • port (Int): A custom port value.
    • activityTimeout (TimeInterval): The interval (in seconds) after which a ping is sent if no messages are received. Low values increase traffic.
    let options = PusherClientOptions(
        authMethod: .endpoint(authEndpoint: "http://localhost:9292/pusher/auth")
    )
    
    let pusher = Pusher(key: "APP_KEY", options: options)