### Initialize and Connect SwiftStomp Source: https://github.com/romixery/swiftstomp/blob/master/README.md Quickly initialize SwiftStomp with a URL, set the delegate, enable auto-reconnect, and establish a connection. ```swift let url = URL(string: "ws://192.168.88.252:8081/socket")! self.swiftStomp = SwiftStomp(host: url) // Create instance self.swiftStomp.delegate = self // Set delegate self.swiftStomp.autoReconnect = true // Auto reconnect on error or cancel self.swiftStomp.connect() // Connect ``` -------------------------------- ### Initialization Source: https://context7.com/romixery/swiftstomp/llms.txt Creates a new SwiftStomp instance with the WebSocket server URL and optional connection headers. ```APIDOC ## Initialization ### Description Creates a new SwiftStomp instance with the WebSocket server URL and optional connection headers for STOMP and HTTP layers. ### Parameters #### Request Body - **host** (URL) - Required - The WebSocket server URL. - **headers** (Dictionary) - Optional - STOMP connection headers. - **httpConnectionHeaders** (Dictionary) - Optional - HTTP connection headers. ``` -------------------------------- ### Initialize SwiftStomp Instance Source: https://context7.com/romixery/swiftstomp/llms.txt Creates a client instance with optional STOMP and HTTP connection headers. ```swift import SwiftStomp // Basic initialization let url = URL(string: "ws://localhost:8080/websocket")! let swiftStomp = SwiftStomp(host: url) // With STOMP connection headers (sent during STOMP CONNECT frame) let swiftStompWithAuth = SwiftStomp( host: url, headers: ["Authorization": "Bearer your-jwt-token"] ) // With both STOMP and HTTP headers let swiftStompFull = SwiftStomp( host: url, headers: ["login": "user", "passcode": "password"], httpConnectionHeaders: ["Cookie": "session=abc123"] ) ``` -------------------------------- ### Connect Source: https://context7.com/romixery/swiftstomp/llms.txt Establishes both WebSocket and STOMP connections to the server. ```APIDOC ## Connect ### Description Establishes both WebSocket and STOMP connections to the server with configurable timeout and protocol version support. ### Parameters #### Request Body - **timeout** (Double) - Optional - Connection timeout in seconds. - **acceptVersion** (String) - Optional - Supported STOMP versions. - **autoReconnect** (Bool) - Optional - Enable auto-reconnect on disconnection. ``` -------------------------------- ### Connect to STOMP Server Source: https://github.com/romixery/swiftstomp/blob/master/README.md Initiates a connection to the STOMP server with a specified timeout and accepted STOMP versions. Ensure you are connected before subscribing. ```Swift self.swiftStomp.connect(timeout: 5.0, acceptVersion: "1.1,1.2") ``` -------------------------------- ### SwiftUI Chat View and ViewModel with SwiftStomp Source: https://context7.com/romixery/swiftstomp/llms.txt This code provides a full SwiftUI view and its associated ViewModel for a chat application. It demonstrates how to initialize SwiftStomp, manage connection states, subscribe to topics, and process incoming messages using Combine. Ensure your STOMP server is running at ws://localhost:8080/gs-guide-websocket. ```swift import SwiftUI import SwiftStomp import Combine struct ChatView: View { @StateObject private var viewModel = ChatViewModel() @State private var messageText = "" var body: some View { VStack { // Connection status HStack { Circle() .fill(viewModel.isConnected ? Color.green : Color.red) .frame(width: 12, height: 12) Text(viewModel.isConnected ? "Connected" : "Disconnected") Spacer() Button(viewModel.isConnected ? "Disconnect" : "Connect") { viewModel.isConnected ? viewModel.disconnect() : viewModel.connect() } } .padding() // Messages list List(viewModel.messages, id: \.self) { message in Text(message) } // Message input HStack { TextField("Message", text: $messageText) .textFieldStyle(RoundedBorderTextFieldStyle()) Button("Send") { viewModel.sendMessage(messageText) messageText = "" } .disabled(!viewModel.isConnected || messageText.isEmpty) } .padding() } } } class ChatViewModel: ObservableObject { @Published var isConnected = false @Published var messages: [String] = [] private var swiftStomp: SwiftStomp private var cancellables = Set() init() { swiftStomp = SwiftStomp( host: URL(string: "ws://localhost:8080/gs-guide-websocket")!, headers: ["Authorization": "Bearer token"] ) swiftStomp.autoReconnect = true swiftStomp.enableAutoPing(pingInterval: 15) // Events upstream swiftStomp.eventsUpstream .receive(on: RunLoop.main) .sink { [weak self] event in switch event { case .connected(let type): if type == .toStomp { self?.isConnected = true self?.swiftStomp.subscribe(to: "/topic/chat", mode: .auto) } case .disconnected: self?.isConnected = false case .error(let error): self?.messages.append("Error: \(error.localizedDescription)") } } .store(in: &cancellables) // Messages upstream swiftStomp.messagesUpstream .receive(on: RunLoop.main) .sink { [weak self] message in if case .text(let content, _, _, _) = message { self?.messages.append(content) } } .store(in: &cancellables) } func connect() { swiftStomp.connect() } func disconnect() { swiftStomp.disconnect() } func sendMessage(_ text: String) { swiftStomp.send(body: text, to: "/app/chat", receiptId: UUID().uuidString) } } ``` -------------------------------- ### Subscribe to a Topic Source: https://github.com/romixery/swiftstomp/blob/master/README.md Subscribes to a STOMP topic. It is recommended to subscribe only when the connection is fully established, ideally within the `onConnect` delegate method when `connectType` is `.toStomp`. ```Swift swiftStomp.subscribe(to: "/topic/greeting", mode: .clientIndividual) ``` -------------------------------- ### Subscribe to SwiftStomp Events with Combine Source: https://github.com/romixery/swiftstomp/blob/master/README.md Use Combine publishers to subscribe to connection and error events. This is particularly useful for SwiftUI projects. ```swift // ** Subscribe to events: [Connect/Disconnect/Errors] swiftStomp.eventsUpstream .receive(on: RunLoop.main) .sink { event in switch event { case let .connected(type): print("Connected with type: \(type)") case .disconnected(_): print("Disconnected with type: \(type)") case let .error(error): print("Error: \(error)") } } .store(in: &subscriptions) // ** Subscribe to messages: [Text/Data] swiftStomp.messagesUpstream .receive(on: RunLoop.main) .sink { message in switch message { case let .text(message, messageId, destination, _): print("\(Date().formatted()) [id: \(messageId), at: \(destination)]: \(message)\n") case let .data(data, messageId, destination, _): print("Data message with id `\(messageId)` and binary length `\(data.count)` received at destination `\(destination)`") } } .store(in: &subscriptions) // ** Subscribe to receipts: [Receipt IDs] swiftStomp.receiptUpstream .sink { receiptId in print("SwiftStop: Receipt received: \(receiptId)") } .store(in: &subscriptions) ``` -------------------------------- ### Implement SwiftStompDelegate in Swift Source: https://context7.com/romixery/swiftstomp/llms.txt Defines a class conforming to SwiftStompDelegate to manage STOMP lifecycle events and message processing. ```swift class StompManager: SwiftStompDelegate { private var swiftStomp: SwiftStomp! init() { let url = URL(string: "ws://localhost:8080/websocket")! swiftStomp = SwiftStomp(host: url) swiftStomp.delegate = self swiftStomp.enableLogging = true swiftStomp.autoReconnect = true } func connect() { swiftStomp.connect() } // Called when connection is established func onConnect(swiftStomp: SwiftStomp, connectType: StompConnectType) { switch connectType { case .toSocketEndpoint: print("WebSocket connected, awaiting STOMP handshake...") case .toStomp: print("STOMP connected! Subscribing to topics...") swiftStomp.subscribe(to: "/topic/messages") swiftStomp.subscribe(to: "/user/queue/notifications", mode: .clientIndividual) } } // Called when disconnection occurs func onDisconnect(swiftStomp: SwiftStomp, disconnectType: StompDisconnectType) { switch disconnectType { case .fromSocket: print("WebSocket disconnected") case .fromStomp: print("STOMP session ended, socket still connected") } } // Called when a message is received func onMessageReceived(swiftStomp: SwiftStomp, message: Any?, messageId: String, destination: String, headers: [String: String]) { if let textMessage = message as? String { print("Text message at \(destination): \(textMessage)") // Acknowledge if using client acknowledgment mode swiftStomp.ack(messageId: messageId) } else if let dataMessage = message as? Data { print("Binary message at \(destination): \(dataMessage.count) bytes") } } // Called when a receipt is received func onReceipt(swiftStomp: SwiftStomp, receiptId: String) { print("Message delivered with receipt: \(receiptId)") } // Called when an error occurs func onError(swiftStomp: SwiftStomp, briefDescription: String, fullDescription: String?, receiptId: String?, type: StompErrorType) { switch type { case .fromSocket: print("Socket error: \(briefDescription)") case .fromStomp: print("STOMP error: \(briefDescription) - \(fullDescription ?? "No details")") } } } ``` -------------------------------- ### Connection Management Source: https://github.com/romixery/swiftstomp/blob/master/README.md Handles connecting to a STOMP server and managing automatic reconnection. ```APIDOC ## Connect to STOMP Server ### Description Establishes a connection to the STOMP server with specified timeout and supported STOMP versions. ### Method `connect` ### Parameters - **timeout** (Double) - The connection timeout in seconds. - **acceptVersion** (String) - The STOMP versions accepted by the client (e.g., "1.1,1.2"). ### Request Example ```swift self.swiftStomp.connect(timeout: 5.0, acceptVersion: "1.1,1.2") ``` ## Auto Reconnect ### Description Enables or disables the automatic reconnection feature. If enabled, the client will attempt to reconnect after unexpected disconnections. ### Property `autoReconnect` (Boolean) ### Usage ```swift // Enable auto reconnect self.swiftStomp.autoReconnect = true // Disable auto reconnect self.swiftStomp.autoReconnect = false ``` ### Notice If `autoReconnect` is enabled and `disconnect()` is called manually, the socket will attempt to reconnect. Disable `autoReconnect` before manual disconnection if this behavior is not desired. ``` -------------------------------- ### Configure Callbacks Thread Source: https://context7.com/romixery/swiftstomp/llms.txt Configures the dispatch queue that receives delegate callbacks and upstream events. By default, callbacks occur on the main queue. ```swift // Default: callbacks on main queue let swiftStomp = SwiftStomp(host: url) // Custom callback queue for background processing swiftStomp.callbacksThread = DispatchQueue(label: "com.app.stomp.callbacks", qos: .userInitiated) // Process messages on background, update UI on main extension MyViewController: SwiftStompDelegate { func onMessageReceived(swiftStomp: SwiftStomp, message: Any?, messageId: String, destination: String, headers: [String: String]) { // This runs on callbacksThread let processed = processMessage(message) DispatchQueue.main.async { self.updateUI(with: processed) } } } ``` -------------------------------- ### SwiftStomp Delegate Methods Source: https://github.com/romixery/swiftstomp/blob/master/README.md Implement these delegate methods to handle STOMP events such as connection, disconnection, message reception, receipts, and errors. ```swift func onConnect(swiftStomp : SwiftStomp, connectType : StompConnectType) func onDisconnect(swiftStomp : SwiftStomp, disconnectType : StompDisconnectType) func onMessageReceived(swiftStomp: SwiftStomp, message: Any?, messageId: String, destination: String, headers : [String : String]) func onReceipt(swiftStomp : SwiftStomp, receiptId : String) func onError(swiftStomp : SwiftStomp, briefDescription : String, fullDescription : String?, receiptId : String?, type : StompErrorType) ``` -------------------------------- ### Subscription Management Source: https://github.com/romixery/swiftstomp/blob/master/README.md Allows subscribing to STOMP destinations to receive messages. ```APIDOC ## Subscribe to a Destination ### Description Subscribes to a specified destination to receive messages. It is recommended to subscribe only when the connection is fully established, ideally within the `onConnect` delegate method. ### Method `subscribe` ### Parameters - **to** (String) - The destination topic to subscribe to (e.g., "/topic/greeting"). - **mode** (SubscriptionMode) - The subscription mode (e.g., `.clientIndividual`). ### Request Example ```swift swiftStomp.subscribe(to: "/topic/greeting", mode: .clientIndividual) ``` ``` -------------------------------- ### Manage STOMP Transactions Source: https://context7.com/romixery/swiftstomp/llms.txt Groups multiple operations atomically using begin, commit, or abort commands. ```swift // Start a transaction swiftStomp.begin(transactionName: "order-tx-001") // Send messages within the transaction swiftStomp.send( body: "Debit account", to: "/app/account", headers: ["transaction": "order-tx-001"] ) swiftStomp.send( body: "Credit account", to: "/app/account", headers: ["transaction": "order-tx-001"] ) // Commit the transaction (all messages are delivered) swiftStomp.commit(transactionName: "order-tx-001") // Or abort the transaction (all messages are discarded) // swiftStomp.abort(transactionName: "order-tx-001") ``` -------------------------------- ### Perform Manual Ping Source: https://context7.com/romixery/swiftstomp/llms.txt Sends a WebSocket ping to verify connectivity, with optional completion handlers and custom data. ```swift // Basic ping swiftStomp.ping() // Ping with completion handler swiftStomp.ping { print("Pong received - connection is alive") } // Ping with custom data swiftStomp.ping(data: "heartbeat".data(using: .utf8)!) { print("Custom ping acknowledged") } ``` -------------------------------- ### Manual Pinging Source: https://github.com/romixery/swiftstomp/blob/master/README.md Enables manual sending of WebSocket 'Ping' messages to the server. ```APIDOC ## Manual Ping ### Description Manually sends a WebSocket 'Ping' message to the server. A 'Pong' message is expected as a response. ### Method `ping` ### Parameters - **data** (Data, optional) - Optional data to include with the ping message. Defaults to empty Data. - **completion** ((() -> Void)?, optional) - A closure to be executed upon receiving a 'Pong' response. ### Request Example ```swift // Send a ping with default data self.swiftStomp.ping() // Send a ping with custom data and a completion handler let customData = "ping_payload".data(using: .utf8) ?? Data() self.swiftStomp.ping(data: customData) { print("Received Pong response!") } ``` ``` -------------------------------- ### Connection Status Source: https://github.com/romixery/swiftstomp/blob/master/README.md Allows checking the current connection status of the SwiftStomp client. ```APIDOC ## Check Connection Status ### Description Retrieves the current connection status of the SwiftStomp client. ### Property `connectionStatus` (ConnectionStatus) ### Usage ```swift switch self.swiftStomp.connectionStatus { case .connecting: print("Connecting to the server...") case .socketConnected: print("Scoket is connected but STOMP as sub-protocol is not connected yet.") case .fullyConnected: print("Both socket and STOMP is connected. Ready for messaging...") case .socketDisconnected: print("Socket is disconnected") } ``` ``` -------------------------------- ### Subscribe Source: https://context7.com/romixery/swiftstomp/llms.txt Subscribes to a STOMP destination to receive messages. ```APIDOC ## Subscribe ### Description Subscribes to a STOMP destination (topic or queue) to receive messages with configurable acknowledgment modes. ### Parameters #### Request Body - **to** (String) - Required - The destination topic or queue. - **mode** (StompAckMode) - Optional - Acknowledgment mode (.auto, .client, .clientIndividual). - **headers** (Dictionary) - Optional - Custom subscription headers. ``` -------------------------------- ### Combine Upstreams for STOMP Events Source: https://context7.com/romixery/swiftstomp/llms.txt Uses Combine publishers to receive STOMP events, messages, and receipts in a reactive programming style. Ideal for SwiftUI applications. ```swift import Combine import SwiftStomp class StompViewModel: ObservableObject { @Published var isConnected = false @Published var messages: [String] = [] @Published var lastError: String? private var swiftStomp: SwiftStomp private var cancellables = Set() init() { let url = URL(string: "ws://localhost:8080/websocket")! swiftStomp = SwiftStomp(host: url) swiftStomp.enableLogging = true swiftStomp.autoReconnect = true setupUpstreams() } private func setupUpstreams() { // Subscribe to connection events swiftStomp.eventsUpstream .receive(on: RunLoop.main) .sink { [weak self] event in guard let self else { return } switch event { case .connected(let type): if type == .toStomp { self.isConnected = true self.swiftStomp.subscribe(to: "/topic/chat") } case .disconnected(_): self.isConnected = false case .error(let error): self.lastError = error.localizedDescription } } .store(in: &cancellables) // Subscribe to incoming messages swiftStomp.messagesUpstream .receive(on: RunLoop.main) .sink { [weak self] message in guard let self else { return } switch message { case .text(let content, let messageId, let destination, let headers): self.messages.append("[\(destination)] \(content)") print("Received \(messageId) with headers: \(headers)") case .data(let data, let messageId, let destination, _): self.messages.append("[\(destination)] Binary: \(data.count) bytes") print("Binary message: \(messageId)") } } .store(in: &cancellables) // Subscribe to receipt confirmations swiftStomp.receiptUpstream .receive(on: RunLoop.main) .sink { receiptId in print("Delivery confirmed: \(receiptId)") } .store(in: &cancellables) } func connect() { swiftStomp.connect() } func disconnect() { swiftStomp.disconnect() } func sendMessage(_ text: String) { swiftStomp.send( body: text, to: "/app/chat", receiptId: UUID().uuidString ) } } ``` -------------------------------- ### Subscribe to Destinations Source: https://context7.com/romixery/swiftstomp/llms.txt Registers a subscription to a topic or queue with specific acknowledgment modes. ```swift // Basic subscription with auto-acknowledge swiftStomp.subscribe(to: "/topic/greetings") // Subscription with client acknowledgment swiftStomp.subscribe(to: "/queue/orders", mode: .client) // Subscription with client-individual acknowledgment swiftStomp.subscribe( to: "/topic/notifications", mode: .clientIndividual, headers: ["selector": "priority > 5"] ) // StompAckMode options: // .auto - Server assumes acknowledgment after sending (default) // .client - Client must send ACK for all messages // .clientIndividual - Client must ACK each message individually ``` -------------------------------- ### Check Connection Status Source: https://context7.com/romixery/swiftstomp/llms.txt Retrieves the current client connection state or detailed status enum. ```swift // Boolean check for fully connected state if swiftStomp.isConnected { print("Ready to send messages") } // Detailed connection status switch swiftStomp.connectionStatus { case .connecting: print("Connecting to server...") case .socketConnected: print("Socket connected, STOMP handshake pending...") case .fullyConnected: print("Fully connected and ready!") case .socketDisconnected: print("Disconnected from server") } ``` -------------------------------- ### Auto Pinging Source: https://github.com/romixery/swiftstomp/blob/master/README.md Configures the client to automatically send 'Ping' messages at a specified interval to keep the connection alive. ```APIDOC ## Auto Ping Configuration ### Description Enables the 'Auto Ping' feature, which periodically sends 'Ping' commands to the WebSocket server to maintain an active connection. This is useful for preventing disconnections due to inactivity. ### Method `enableAutoPing` ### Parameters - **pingInterval** (TimeInterval) - The interval in seconds between automatic ping messages. Defaults to 10 seconds. ### Usage ```swift // Enable auto ping with default interval (10 seconds) self.swiftStomp.enableAutoPing() // Enable auto ping with a custom interval of 30 seconds self.swiftStomp.enableAutoPing(pingInterval: 30) ``` ### Disable Auto Ping ### Method `disableAutoPing` ### Usage ```swift self.swiftStomp.disableAutoPing() ``` ### Notice - Auto ping is disabled by default and must be explicitly enabled after connecting to the server. - If the connection is disconnected manually or unexpectedly, `enableAutoPing()` must be called again to re-enable the feature. ``` -------------------------------- ### Send Message Source: https://context7.com/romixery/swiftstomp/llms.txt Sends a message (String or Data) to a STOMP destination. ```APIDOC ## Send Message ### Description Sends a text or binary message to a STOMP destination with optional receipt tracking and custom headers. ### Parameters #### Request Body - **body** (String/Data) - Required - The message content. - **to** (String) - Required - The destination path. - **receiptId** (String) - Optional - Receipt ID for delivery confirmation. - **headers** (Dictionary) - Optional - Custom message headers. ``` -------------------------------- ### Send a Message Source: https://github.com/romixery/swiftstomp/blob/master/README.md Sends a message with a specified body, destination, optional receipt ID, and headers. The receipt ID can be dynamically generated. ```Swift swiftStomp.send(body: "This is message's text body", to: "/app/greeting", receiptId: "msg-\(Int.random(in: 0..<1000))", headers: [:]) ``` -------------------------------- ### Manual Ping Source: https://github.com/romixery/swiftstomp/blob/master/README.md Manually sends a WebSocket 'Ping' message. A 'Pong' message is expected as a response. This function can optionally accept completion handler. ```Swift func ping(data: Data = Data(), completion: (() -> Void)? = nil) ``` -------------------------------- ### Configure Auto Ping Source: https://context7.com/romixery/swiftstomp/llms.txt Enables or disables periodic WebSocket pings to maintain idle connections. ```swift // Enable auto-ping with default 10-second interval swiftStomp.enableAutoPing() // Enable auto-ping with custom interval swiftStomp.enableAutoPing(pingInterval: 30) // Every 30 seconds // Disable auto-ping swiftStomp.disableAutoPing() // Note: Auto-ping is disabled by default and must be re-enabled after reconnection ``` -------------------------------- ### Disconnect from Server Source: https://context7.com/romixery/swiftstomp/llms.txt Gracefully closes the connection or forces an immediate socket termination. ```swift // Graceful disconnect (sends STOMP DISCONNECT frame first) swiftStomp.disconnect() // Force disconnect (closes socket immediately without STOMP DISCONNECT) swiftStomp.disconnect(force: true) // Check connection before disconnecting if swiftStomp.isConnected { swiftStomp.disconnect() } ``` -------------------------------- ### Enable Auto Ping Source: https://github.com/romixery/swiftstomp/blob/master/README.md Enables the 'Auto Ping' feature to maintain connection liveness by sending periodic 'ping' commands to the WebSocket server. This must be enabled after connecting and re-enabled if disconnected or `disconnect()` is called. Auto ping is disabled by default. ```Swift func enableAutoPing(pingInterval: TimeInterval = 10) ``` -------------------------------- ### Enable/Disable STOMP Logging Source: https://context7.com/romixery/swiftstomp/llms.txt Enables or disables debug logging for connection events and STOMP frame details. Useful for debugging connection issues. ```swift // Enable logging swiftStomp.enableLogging = true // Connect and observe console output: // 2024-05-17 10:30:45 SwiftStomp [info]: Connecting... // 2024-05-17 10:30:45 SwiftStomp [info]: Socket: connected // 2024-05-17 10:30:45 SwiftStomp [info]: Stomp: Sending CONNECT frame // 2024-05-17 10:30:45 SwiftStomp [info]: Stomp: Connected // Disable logging for production swiftStomp.enableLogging = false ``` -------------------------------- ### Check Connection Status Source: https://github.com/romixery/swiftstomp/blob/master/README.md Checks the current connection status of the SwiftStomp client. This allows for conditional logic based on whether the client is connecting, connected, or disconnected. ```Swift switch self.swiftStomp.connectionStatus { case .connecting: print("Connecting to the server...") case .socketConnected: print("Scoket is connected but STOMP as sub-protocol is not connected yet.") case .fullyConnected: print("Both socket and STOMP is connected. Ready for messaging...") case .socketDisconnected: print("Socket is disconnected") } ``` -------------------------------- ### Enable Auto Reconnect Source: https://github.com/romixery/swiftstomp/blob/master/README.md Enables automatic reconnection attempts after unexpected disconnections. Note that if autoReconnect is enabled, manually disconnecting will also trigger a reconnection attempt unless disabled beforehand. ```Swift self.swiftStomp.autoReconnect = true ``` -------------------------------- ### Send Binary Data Source: https://context7.com/romixery/swiftstomp/llms.txt Transmits binary payloads for file transfers or custom protocols. ```swift // Send binary data let imageData = UIImage(named: "photo")?.jpegData(compressionQuality: 0.8) if let data = imageData { swiftStomp.send( body: data, to: "/app/upload", receiptId: "upload-001", headers: ["content-type": "image/jpeg"] ) } ``` -------------------------------- ### Message Sending Source: https://github.com/romixery/swiftstomp/blob/master/README.md Provides functionality to send messages to a specified destination with optional headers and receipt IDs. ```APIDOC ## Send Message ### Description Sends a message payload to a specified destination. Allows for custom headers and a unique receipt ID for tracking. ### Method `send` ### Parameters - **body** (String) - The content of the message to send. - **to** (String) - The destination endpoint for the message (e.g., "/app/greeting"). - **receiptId** (String, optional) - A unique identifier for the message receipt. - **headers** (Dictionary, optional) - Additional headers to include with the message. ### Request Example ```swift swiftStomp.send(body: "This is message's text body", to: "/app/greeting", receiptId: "msg-\(Int.random(in: 0..<1000))", headers: [:]) ``` ``` -------------------------------- ### Send Encodable Message with SwiftStomp Source: https://context7.com/romixery/swiftstomp/llms.txt Serializes Encodable objects to JSON for transmission. Supports custom date encoding strategies and optional receipt headers. ```swift struct ChatMessage: Encodable { let sender: String let content: String let timestamp: Date } let message = ChatMessage( sender: "user123", content: "Hello everyone!", timestamp: Date() ) // Send with default ISO8601 date encoding swiftStomp.send( body: message, to: "/app/chat" ) // Send with custom date encoding strategy swiftStomp.send( body: message, to: "/app/chat", receiptId: "chat-001", headers: ["content-type": "application/json"], jsonDateEncodingStrategy: .millisecondsSince1970 ) ``` -------------------------------- ### Send Text Messages Source: https://context7.com/romixery/swiftstomp/llms.txt Transmits string-based messages with optional receipt tracking and custom headers. ```swift // Basic text message swiftStomp.send(body: "Hello, World!", to: "/app/chat") // Message with receipt ID for delivery confirmation swiftStomp.send( body: "Important message", to: "/app/orders", receiptId: "msg-\(UUID().uuidString)" ) // Message with custom headers swiftStomp.send( body: "Notification content", to: "/app/notifications", receiptId: "notify-001", headers: [ "content-type": "text/plain", "priority": "high" ] ) ``` -------------------------------- ### Acknowledge Messages with ACK Source: https://context7.com/romixery/swiftstomp/llms.txt Confirms receipt of messages in client acknowledgment mode, optionally within a transaction. ```swift // Simple acknowledgment swiftStomp.ack(messageId: "message-12345") // Acknowledgment within a transaction swiftStomp.ack( messageId: "message-12345", transaction: "tx-001" ) ``` -------------------------------- ### Unsubscribe from Destinations Source: https://context7.com/romixery/swiftstomp/llms.txt Removes an existing subscription to stop receiving messages. ```swift // Basic unsubscribe swiftStomp.unsubscribe(from: "/topic/greetings") // Unsubscribe with custom headers swiftStomp.unsubscribe( from: "/queue/orders", headers: ["custom-header": "value"] ) ``` -------------------------------- ### Negative Acknowledge Messages with NACK Source: https://context7.com/romixery/swiftstomp/llms.txt Signals processing failure for a message, optionally scoped to a transaction. ```swift // Simple negative acknowledgment swiftStomp.nack(messageId: "message-12345") // NACK within a transaction swiftStomp.nack( messageId: "message-12345", transaction: "tx-001" ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.