NWWebSocket

repository·main·Indexed 41 days ago

https://github.com/pusher/nwwebsocket

A Swift-based WebSocket client built on Apple's Network framework. It provides a high-level API for managing WebSocket connections, sending UTF-8 strings or binary data, and handling connection lifecycle events via the WebSocketConnectionDelegate protocol. Supports installation via CocoaPods and Swift Package Manager.

Tokens
1.7K
Snippets
6
Records
6
Agent score
1%

What's inside NWWebSocket

  1. Install NWWebSocket via Swift Package Manager

    main

    You can add NWWebSocket as a dependency in Xcode using the repository URL: https://github.com/pusher/NWWebSocket.git

    Alternatively, add it directly to your Package.swift file:

    // 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/NWWebSocket.git",
                     .upToNextMajor(from: "0.5.10")),
        ],
        targets: [
            .target(
                name: "YourPackage",
                dependencies: ["NWWebSocket"]),
        ]
    )

    Note: You must include both import Network and import NWWebSocket 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/NWWebSocket.git",
                     .upToNextMajor(from: "0.5.10")),
        ],
        targets: [
            .target(
                name: "YourPackage",
                dependencies: ["NWWebSocket"]),
        ]
    )
  2. Install NWWebSocket via CocoaPods

    main

    To integrate NWWebSocket into your Xcode project using CocoaPods, add the following to your Podfile:

    pod 'NWWebSocket', '~> 0.5.10'

    Then, run pod install in your terminal. If you encounter issues with the version not being current, try cleaning the cache and updating the repo:

    $ pod cache clean
    $ pod repo update NWWebSocket
    $ pod install
    source 'https://github.com/CocoaPods/Specs.git'
    platform :ios, '14.0'
    use_frameworks!
    
    pod 'NWWebSocket', '~> 0.5.10'
  3. Connect and disconnect from a WebSocket

    main

    You can manage connections manually or automatically. By default, connections are manual. Setting connectAutomatically: true during initialization will trigger the connection immediately.

    In both cases, you must assign a delegate that conforms to WebSocketConnectionDelegate to handle lifecycle events and messages.

    // Manual connection
    let socketURL = URL(string: "wss://somewebsockethost.com")
    let socket = NWWebSocket(url: socketURL)
    socket.delegate = self
    socket.connect()
    
    // Use the WebSocket…
    
    socket.disconnect()
  4. Send string or binary data over NWWebSocket

    main

    Use the send(string:) method for UTF-8 encoded strings or send(data:) for binary data.

    // Sending a `String`
    let message = "Hello, world!"
    socket.send(string: message)
    
    // Sending some binary data
    let data: [UInt8] = [123, 234]
    let messageData = Data(data)
    socket.send(data: messageData)
  5. Use Ping to maintain a connection

    main

    To prevent connection closure, especially when messages are sent infrequently, you can trigger a Ping. You can trigger a Ping on-demand or set a periodic interval.

    // Trigger a Ping on demand
    socket.ping()
    
    // Trigger a Ping periodically
    // (This is useful when messages are infrequently sent across the connection to prevent a connection closure)
    socket.ping(interval: 30.0)
  6. Implement WebSocketConnectionDelegate to receive messages and updates

    main

    To handle incoming messages (strings or binary data) and connection lifecycle events (connect, disconnect, errors, viability changes), your class must conform to the WebSocketConnectionDelegate protocol.

    extension MyWebSocketConnectionManager: WebSocketConnectionDelegate {
    
        func webSocketDidConnect(connection: WebSocketConnection) {
            // Respond to a WebSocket connection event
        }
    
        func webSocketDidDisconnect(connection: WebSocketConnection, 
                                    closeCode: NWProtocolWebSocket.CloseCode, 
                                    reason: Data?) {
            // Respond to a WebSocket disconnection event
        }
    
        func webSocketViabilityDidChange(connection: WebSocketConnection, isViable: Bool) {
            // Respond to a WebSocket connection viability change event
        }
    
        func webSocketDidAttemptBetterPathMigration(result: Result<WebSocketConnection, NWError>) {
            // Respond to when a WebSocket connection migrates to a better network path
        }
    
        func webSocketDidReceiveError(connection: WebSocketConnection, error: NWError) {
            // Respond to a WebSocket error event
        }
    
        func webSocketDidReceivePong(connection: WebSocketConnection) {
            // Respond to a WebSocket connection receiving a Pong from the peer
        }
    
        func webSocketDidReceiveMessage(connection: WebSocketConnection, string: String) {
            // Respond to a WebSocket connection receiving a `String` message
        }
    
        func webSocketDidReceiveMessage(connection: WebSocketConnection, data: Data) {
            // Respond to a WebSocket connection receiving a binary `Data` message
        }
    }