GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — GitHub - Recouse/EventSource: Server-sent events in Swift

BranchesTags
Open more actions menu

Latest commit

 

History

142 Commits
142 Commits

Folders and files

NameName
Last commit message
Last commit date
.github
.github
 
 
.swiftpm/xcode/package.xcworkspace/xcshareddata
.swiftpm/xcode/package.xcworkspace/xcshareddata
 
 
Sources/EventSource
Sources/EventSource
 
 
Tests/EventSourceTests
Tests/EventSourceTests
 
 
.gitignore
.gitignore
 
 
CODE_OF_CONDUCT.md
CODE_OF_CONDUCT.md
 
 
CONTRIBUTING.md
CONTRIBUTING.md
 
 
LICENSE
LICENSE
 
 
Package.swift
Package.swift
 
 
README.md
README.md
 
 

Repository files navigation

EventSource

CI

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.

Features

  • Simple Swift API for SSE
  • Supports data-only mode
  • Data race safety with Swift 6

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 data 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 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.")
        }
    }
}

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

Data-only mode

EventSource can be used in data-only mode, making it suitable for popular APIs like OpenAI. Below is an example using OpenAI's completions API:

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)
}

Compatibility

  • macOS 10.15+
  • iOS 13.0+
  • tvOS 13.0+
  • watchOS 6.0+
  • visionOS 1.0+

Dependencies

No dependencies.

Contributing

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

Credits

  • Mutex backport from swift-sharing

License

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

About

Server-sent events in Swift

Topics

clientevent-sourceeventsourceserver-sent-eventssse

Resources

Readme
MIT license

Code of conduct

Code of conduct

Contributing

Contributing
Activity

Stars

161 stars

Watchers

2 watching

Forks

28 forks
Report repository

Releases

Sponsor this project

Used by

Contributors

Languages

You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.