Recouse / EventSource

Server-sent events in Swift
MIT License
37 stars 8 forks source link
client event-source eventsource server-sent-events sse

EventSource

Build macOS Build Linux

EventSource is a Swift package that provides a simple implementation of a client for Server-Sent Events (SSE). It allows you to easily receive real-time updates from a server over a persistent HTTP connection, using a simple and efficient interface.

It also leverages Swift concurrency features to provide a more expressive and intuitive way to handle asynchronous operations.

[!Note] Please note that this package was originally developed to be used in conjunction with another package, and as such, it may not cover all specification details. Please be aware of this limitation when evaluating whether EventSource is suitable for your specific use case.

Installation

The module name of the package is EventSource. Choose one of the instructions below to install and add the following import statement to your source code.

import EventSource

Xcode Package Dependency

From Xcode menu: File > Swift Packages > Add Package Dependency

https://github.com/Recouse/EventSource

Swift Package Manager

In your Package.swift file, first add the following to the package dependencies:

.package(url: "https://github.com/Recouse/EventSource.git"),

And then, include "EventSource" as a dependency for your target:

.target(name: "<target>", dependencies: [
    .product(name: "EventSource", package: "EventSource"),
]),

Usage

Using EventSource is easy. Simply create a new task from an instance of EventSource with the URLRequest of the SSE endpoint you want to connect to, and await for events:

import EventSource

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 .message(let message):
        print("Received a message", message.data ?? "")
    case .closed:
        print("Connection was closed.")
    }
}

Use dataTask.cancel() to explicitly close the connection. However, in that case .closed event won't be emitted.

Compatibility

Dependencies

No dependencies.

Contributing

Contributions to are always welcomed! For more details see CONTRIBUTING.md.

License

EventSource is released under the MIT License. See LICENSE for more information.