launchdarkly / swift-eventsource

Server-sent events (SSE) client implementation in Swift for iOS, macOS, tvOS, and watchOS
https://launchdarkly.github.io/swift-eventsource/
Other
187 stars 34 forks source link

Can provide a simple example of use this repo? #53

Closed tesths closed 1 year ago

tesths commented 1 year ago

Is your feature request related to a problem? Please describe. Recent I am try to use Event Source in my project, when I search on Github, only this repo is really perfect. But I am new to iOS, I use many time try to use it in my project, try to under the LaunchDarkly SDK and other user project, but still under stand, and my project still can't work. Can this repo provide simple example use in iOS or Mac project? I already try in my ContentView, but really no response.

let es = EventSource(config: config)
es.start()

Describe the solution you'd like Provide a simple project use this excellent repo.

Additional context Thanks for upload this project in Github.

keelerm84 commented 1 year ago

Hello and thank you for opening this issue!

There are some API docs for this package available on GH Pages. While they do not provide examples at this time, they do at least cover some specifics in a more discoverable format so I wanted to make sure you were aware of those resources.

As for an example, I have included something below that I hope will help. As you can see, the key is registering a handler with the EventSource as that is the mechanism used to notify the consumer of changes in the network digest.

I will also file a task internally for us to help provide some more guidance on how to use this package.

Let me know if you have any questions!

import LDSwiftEventSource
import Foundation

class YourCustomHandler: EventHandler
{
    func onOpened() { print("The connection is open") }
    func onClosed() { print("The connection is closed") }
    func onMessage(eventType: String, messageEvent: MessageEvent) { print("A message has been received of type \(eventType)") }
    func onComment(comment: String) { print("A comment has been received: \(comment)") }
    func onError(error: Error) { print("An error has occurred \(error)") }
}

var config = EventSource.Config(handler: YourCustomHandler(), url: URL(string: "YOUR EVENT STREAM URL")!)
config.headers = ["Authorization": "REQUIRED TOKEN", "Content-Type": "application/json", "Accept": "application/json"]

var eventsource = EventSource(config: config)
eventsource.start()

let semaphore = DispatchSemaphore(value: 0)
let runLoop = RunLoop.current

while semaphore.wait(timeout: .now()) == .timedOut {
    runLoop.run(mode: .default, before: .distantFuture)
}