A simple Swift client library for the Server Side Events also known as SSE.
EventSource.Swift is an client implementation of the HTML 5 EventSource API that allows browsers respond to SSE event-streams EventSource.
Swift will work on both OSX and iOS.
It was heavily inspired by the Objective-C client found here: EventSource
If you're interested in EventSource.Swift, you might be interested in FayeSwift too. I wrote this client with the intention of adding a SSE transport for FayeSwift, a swift Faye client. FayeSwift currently only websocket transports.
For now, add EventSource.swift
to your project.
You can open a connection to your faye server.
var source = EventSource(url: "http://127.0.0.1:8000/")
You can then add an event listener for any event:
source.addEventListener("hello_event", handler: { (e:Event) -> Void in
println("Event: \(e.event) Data: \(e.data)")
})
After you are connected, there are some optional delegate methods that we can implement.
You can subscribe to the following EventTypes
to observer all respective data as it comes in:
source.onOpen { (e:Event) -> Void in
println("Connection opened!")
}
source.onError { (e:Event) -> Void in
println("Error: \(e.error?.userInfo)")
}
source.onMessage { (e:Event) -> Void in
println("Message: \(e.data)");
}
First set the delegate on the EventSource
instance:
source.delegate = self
You can then implement the EventSourceDelegate
in addition or instead of the callback handlers mentioned above.
func eventSourceOpenedConnection(event: Event) {
println("DELEGATE: OPENED CONNECTION")
}
func eventSourceReceivedError(event: Event, error: NSError) {
println("DELEGATE: Received Error: \(error)")
}
func eventSourceReceivedMessage(event: Event, message: NSDictionary) {
println("DELEGATE: RECEIVED MESSAGE: \(message)")
}
There is a sample EventSource server using the NodeJS Faye library. If you have NodeJS just start the server like so:
node server.js
Check out the EventSourceSwiftDemo project to see how to setup a simple connection to a EventSource server.
EventSource.Swift requires at least iOS 7/OSX 10.10 or above.
- Replace NSURLConnection with NSURLSession
- Cocoapods Integration
- Complete Docs
- Add Unit Tests
EventSource.Swift is licensed under the MIT License.