### Initialize EventSource in Swift Source: https://context7.com/recouse/eventsource/llms.txt This snippet demonstrates how to initialize EventSource instances with various configurations, including standard SSE mode, data-only mode, custom timeouts, and event parsers. It relies on the EventSource package and is designed for Swift environments. Inputs include optional mode, timeoutInterval, and eventParser parameters; outputs are configured EventSource objects. Note that it requires Swift 6 for concurrency safety and may not support all non-standard SSE formats without custom parsers. ```swift import EventSource // Standard SSE mode with default timeout (300 seconds) let eventSource = EventSource() // Data-only mode for simplified APIs (like OpenAI) let streamingEventSource = EventSource(mode: .dataOnly) // Custom timeout (60 seconds) let shortTimeoutEventSource = EventSource(timeoutInterval: 60) // Custom parser for non-standard formats let customEventSource = EventSource( mode: .default, eventParser: MyCustomParser(), timeoutInterval: 120 ) ``` -------------------------------- ### Connect to SSE Endpoint in Swift Source: https://context7.com/recouse/eventsource/llms.txt This snippet shows how to establish a connection to an SSE endpoint and process streaming events using async/await in Swift. It depends on the EventSource and Foundation frameworks for URL handling and concurrency tasks. Inputs are a URLRequest; outputs include event streams (open, event data, errors, closed) for real-time processing. Limitations include reliance on server compliance with SSE standards and potential network timeouts as configured. ```swift import EventSource import Foundation Task { let eventSource = EventSource() let url = URL(string: "https://example.com/events")! let urlRequest = URLRequest(url: url) let dataTask = eventSource.dataTask(for: urlRequest) do { for await event in dataTask.events() { switch event { case .open: print("āœ“ Connection established") print("State: \(dataTask.readyState)") case .event(let serverEvent): print("Event Type: \(serverEvent.event ?? "message")") print("Event ID: \(serverEvent.id ?? "none")") print("Data: \(serverEvent.data ?? "")") // Handle specific event types if serverEvent.event == "update" { // Process update event } else if serverEvent.event == "notification" { // Process notification event } case .error(let error): print("āœ— Error: \(error.localizedDescription)") if let esError = error as? EventSourceError { switch esError { case .connectionError(let statusCode, let response): print("HTTP \(statusCode): \(String(data: response, encoding: .utf8) ?? "")") default: break } } case .closed: print("āœ“ Connection closed gracefully") break } } } } ``` -------------------------------- ### Monitor Live Data Feeds with EventSource in Swift Source: https://context7.com/recouse/eventsource/llms.txt Implements a live data monitor using EventSource that connects to a specified URL, processes incoming Server-Sent Events, and includes connection monitoring with reconnection logic. It utilizes an actor for thread-safe management of the data task and connection. ```swift import EventSource import Foundation actor LiveDataMonitor { private var dataTask: EventSource.DataTask? private var connectionTask: Task? func connect(to url: URL) { connectionTask?.cancel() connectionTask = Task { let eventSource = EventSource(timeoutInterval: 120) var urlRequest = URLRequest(url: url) // Add Last-Event-ID for reconnection if let lastId = dataTask?.lastMessageId, !lastId.isEmpty { urlRequest.setValue(lastId, forHTTPHeaderField: "Last-Event-ID") print("Reconnecting with Last-Event-ID: (lastId)") } let newDataTask = eventSource.dataTask(for: urlRequest) self.dataTask = newDataTask for await event in newDataTask.events() { print("State: (newDataTask.readyState.description)") switch event { case .open: print("šŸ“” Connected to live feed") case .event(let serverEvent): // Store event ID for reconnection if let id = serverEvent.id { print("Last Event ID: (id)") } // Process data if let jsonData = serverEvent.data?.data(using: .utf8) { handleLiveData(jsonData) } case .error(let error): print("šŸ“” Connection error: (error)") // Implement retry logic try? await Task.sleep(nanoseconds: 5_000_000_000) // 5 seconds connect(to: url) case .closed: print("šŸ“” Connection closed") } } } } func disconnect() { connectionTask?.cancel() dataTask = nil } private func handleLiveData(_ data: Data) { // Process incoming data if let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] { print("Received: (json)") } } } extension EventSource.ReadyState: CustomStringConvertible { public var description: String { switch self { case .none: return "none" case .connecting: return "connecting" case .open: return "open" case .closed: return "closed" } } } // Usage let monitor = LiveDataMonitor() await monitor.connect(to: URL(string: "https://api.example.com/live-feed")!) // Later, disconnect await monitor.disconnect() ``` -------------------------------- ### Configure URLRequest with Auth, Headers, and POST Data for EventSource Source: https://context7.com/recouse/eventsource/llms.txt Configures a URLRequest for use with EventSource, including setting the HTTP method to POST, adding authentication tokens, custom headers, and a JSON request body. It also sets the cache policy and notes headers automatically added by EventSource. The code demonstrates consuming events via an async stream. ```swift import EventSource import Foundation Task { var urlRequest = URLRequest(url: URL(string: "https://secure-api.example.com/stream")!) // HTTP method (default is GET, but can use POST for streaming APIs) urlRequest.httpMethod = "POST" // Authentication urlRequest.setValue("Bearer (accessToken)", forHTTPHeaderField: "Authorization") // Custom headers urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") urlRequest.setValue("gzip, deflate", forHTTPHeaderField: "Accept-Encoding") urlRequest.setValue("MyApp/1.0", forHTTPHeaderField: "User-Agent") // Request body for POST let requestBody: [String: Any] = [ "query": "subscribe", "topics": ["news", "updates"], "format": "json" ] urlRequest.httpBody = try! JSONSerialization.data(withJSONObject: requestBody) // Cache policy urlRequest.cachePolicy = .reloadIgnoringLocalCacheData // Note: EventSource automatically adds: // - Accept: text/event-stream // - Cache-Control: no-store let eventSource = EventSource(timeoutInterval: 180) let dataTask = eventSource.dataTask(for: urlRequest) for await event in dataTask.events() { switch event { case .event(let serverEvent): print("Received: (serverEvent.data ?? "")") default: break } } } ``` -------------------------------- ### SSE Client with Retry Logic in Swift Source: https://context7.com/recouse/eventsource/llms.txt Implements resilient SSE connection with automatic retry and exponential backoff. Handles network errors, HTTP status codes, and cancellation. Maximum 5 retries with delay up to 32 seconds. ```swift import EventSource import Foundation actor ResilientSSEClient { private var connectionTask: Task? private var retryCount = 0 private let maxRetries = 5 func connect(to url: URL) { connectionTask?.cancel() retryCount = 0 connectionTask = Task { await connectWithRetry(url: url) } } private func connectWithRetry(url: URL) async { while retryCount < maxRetries && !Task.isCancelled { let eventSource = EventSource(timeoutInterval: 60) let urlRequest = URLRequest(url: url) let dataTask = eventSource.dataTask(for: urlRequest) var shouldRetry = false for await event in dataTask.events() { switch event { case .open: retryCount = 0 // Reset on successful connection print("āœ“ Connected successfully") case .event(let serverEvent): // Process event if let data = serverEvent.data { print("Data: \(data)") } case .error(let error): print("āœ— Error: \(error.localizedDescription)") if let esError = error as? EventSourceError { switch esError { case .connectionError(let statusCode, _): // Retry on 5xx errors, not on 4xx shouldRetry = statusCode >= 500 print("HTTP \(statusCode) - Retry: \(shouldRetry)") case .undefinedConnectionError: shouldRetry = true case .alreadyConsumed: shouldRetry = false } } else { // Network errors - retry shouldRetry = true } case .closed: print("Connection closed") shouldRetry = true } } // Implement retry with exponential backoff if shouldRetry && retryCount < maxRetries { retryCount += 1 let delay = min(pow(2.0, Double(retryCount)), 32.0) // Max 32 seconds print("ā³ Retrying in \(delay) seconds (attempt \(retryCount)/\(maxRetries))") try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000)) } else { break } } if retryCount >= maxRetries { print("āœ— Max retries reached. Giving up.") } } func disconnect() { connectionTask?.cancel() connectionTask = nil } } // Usage let client = ResilientSSEClient() await client.connect(to: URL(string: "https://api.example.com/events")!) ``` -------------------------------- ### Connect to SSE Endpoint with Swift Concurrency Source: https://github.com/recouse/eventsource/blob/main/README.md Establishes a connection to a Server-Sent Events endpoint using Swift concurrency. It handles opening, receiving, and closing events, and provides error handling. Requires the EventSource package. ```swift import EventSource let task = Task { let eventSource = EventSource() let dataTask = eventSource.dataTask(for: urlRequest) for await event in dataTask.events() { switch event { case .open: print("Connection was opened.") case .error(let error): print("Received an error:", error.localizedDescription) case .event(let event): print("Received an event", event.data ?? "") case .closed: print("Connection was closed.") } } } ``` -------------------------------- ### Consume OpenAI Streaming API with EventSource in Swift Source: https://context7.com/recouse/eventsource/llms.txt Integrates with OpenAI's chat completions API to receive streaming responses. It sends a POST request with chat messages and processes the stream chunk by chunk, printing the content as it arrives. Requires API key and handles connection events and errors. ```swift import EventSource import Foundation struct ChatChunk: Codable { struct Delta: Codable { let content: String? } struct Choice: Codable { let delta: Delta } let choices: [Choice] } Task { let apiKey = "sk-…" var urlRequest = URLRequest(url: URL(string: "https://api.openai.com/v1/chat/completions")!) urlRequest.httpMethod = "POST" urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") urlRequest.setValue("Bearer (apiKey)", forHTTPHeaderField: "Authorization") let requestBody: [String: Any] = [ "model": "gpt-4o-mini", "messages": [ ["role": "user", "content": "Write a haiku about Swift programming"] ], "stream": true ] urlRequest.httpBody = try! JSONSerialization.data(withJSONObject: requestBody) let eventSource = EventSource(mode: .dataOnly) let dataTask = eventSource.dataTask(for: urlRequest) var fullResponse = "" for await event in dataTask.events() { switch event { case .event(let serverEvent): guard let data = serverEvent.data else { continue } // Handle [DONE] signal if data == "[DONE]" { print("\nāœ“ Stream complete") break } // Parse JSON chunk if let jsonData = data.data(using: .utf8), let chunk = try? JSONDecoder().decode(ChatChunk.self, from: jsonData), let content = chunk.choices.first?.delta.content { fullResponse += content print(content, terminator: "") fflush(stdout) } case .error(let error): print("\nāœ— Streaming error: (error)") default: break } } print("\n\nFull Response: (fullResponse)") } ``` -------------------------------- ### Implement Custom SSE Event Parser in Swift Source: https://context7.com/recouse/eventsource/llms.txt This snippet shows how to define a custom event structure conforming to EVEvent and implement an EventParser protocol to handle non-standard SSE data. It includes logic for splitting data by lines and parsing custom formats, managing a buffer for incomplete data, and integrating the custom parser with EventSource. ```swift import EventSource import Foundation // Custom event structure struct CustomEvent: EVEvent { var id: String? var event: String? var data: String? var other: [String: String]? var time: String? var customField: String? // Additional field } // Custom parser implementation struct CustomEventParser: EventParser { private var buffer = Data() mutating func parse(_ data: Data) -> [EVEvent] { buffer.append(data) var events: [EVEvent] = [] // Custom parsing logic let lines = buffer.split(separator: UInt8(ascii: "\n")) for line in lines { guard let lineString = String(data: Data(line), encoding: .utf8) else { continue } // Example: Parse custom format like "TYPE|ID|DATA" let components = lineString.split(separator: "|") if components.count >= 3 { let event = CustomEvent( id: String(components[1]), event: String(components[0]), data: String(components[2]), other: nil, time: nil, customField: components.count > 3 ? String(components[3]) : nil ) events.append(event) } } // Clear buffer after processing if !events.isEmpty { buffer.removeAll() } return events } } // Usage with custom parser Task { let eventSource = EventSource( mode: .default, eventParser: CustomEventParser(), timeoutInterval: 300 ) let urlRequest = URLRequest(url: URL(string: "https://api.custom.com/events")!) let dataTask = eventSource.dataTask(for: urlRequest) for await event in dataTask.events() { if case .event(let serverEvent) = event, let customEvent = serverEvent as? CustomEvent { print("Custom Field: (customEvent.customField ?? "none")") } } } ``` -------------------------------- ### Static SSE Event Parsing in Swift Source: https://context7.com/recouse/eventsource/llms.txt Parses Server-Sent Events from static data without connection. Supports standard SSE format, data-only payloads, and multi-line data. Demonstrates different parsing modes and field extraction. ```swift import EventSource import Foundation // Parse standard SSE format let sseData = """ id: 123 event: notification data: {"message": "Hello World"} id: 124 event: update data: {"status": "complete"} data: {"progress": 100} """.data(using: .utf8)! if let event = ServerEvent.parse(from: sseData, mode: .default) { print("Event ID: \(event.id ?? "none")") print("Event Type: \(event.event ?? "message")") print("Data: \(event.data ?? "")") print("Is Empty: \(event.isEmpty)") } // Parse data-only format let dataOnlyPayload = """ data: {"content": "Swift is awesome"} """.data(using: .utf8)! if let event = ServerEvent.parse(from: dataOnlyPayload, mode: .dataOnly) { print("Data: \(event.data ?? "")") } // Multi-line data handling let multiLineData = """ event: message data: Line 1 data: Line 2 data: Line 3 """.data(using: .utf8)! if let event = ServerEvent.parse(from: multiLineData, mode: .default) { // Multi-line data is concatenated with newlines print("Multi-line Data: \(event.data ?? "")") // Output: "Line 1\nLine 2\nLine 3" } ``` -------------------------------- ### Data-Only Mode for SSE with Swift Concurrency Source: https://github.com/recouse/eventsource/blob/main/README.md Utilizes EventSource in data-only mode to process streaming responses, such as from OpenAI's chat completions API. It decodes incoming data chunks to reconstruct the full response. Requires the EventSource package and a defined `ChatCompletionChunk` structure. ```swift Task { var urlRequest = URLRequest(url: URL(string: "https://api.openai.com/v1/chat/completions")!) urlRequest.allHTTPHeaderFields = [ "Content-Type": "application/json", "Authorization": "Bearer (accessToken)" ] urlRequest.httpMethod = "POST" urlRequest.httpBody = """ { "model": "gpt-4o-mini", "messages": [ {"role": "user", "content": "Why is the sky blue?"} ], "stream": true } """.data(using: .utf8)! let eventSource = EventSource(mode: .dataOnly) let dataTask = eventSource.dataTask(for: urlRequest) var response: String = "" for await event in dataTask.events() { switch event { case .event(let event): if let data = eventDevent.data?.data(using: .utf8) { let chunk = try? JSONDecoder().decode(ChatCompletionChunk.self, from: data) let string = chunk?.choices.first?.delta.content ?? "" response += string } default: break } } print(response) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.