• Stars
    star
    483
  • Rank 91,050 (Top 2 %)
  • Language
    Swift
  • License
    Apache License 2.0
  • Created almost 10 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A simple Swift client library for the Server Sent Events (SSE)

EventSource

EventSource

SSE Client written on Swift using NSURLSession.

Build Status codecov.io codecov.io

Abstract

This is an EventSource implementation written on Swift following the W3C EventSource document. If something is missing or not completely right open an issue and I'll work on it!

If you like the library please leave us a โ˜…. That helps us to stay engaged on the mantainence!

Changes from version 2.2.1 to 3.0

I took some time to review all the forks, pull requests and issues opened on github. The main changes and complains I found were related to the connection and the Last-Event-Id handling.

The changes on this version are:

  • EventSource doesn't connect automatically anymore. It waits until connect(lastEventId: String? = nil) method is called. This method accepts a lastEventId which will be sent to the server upon connection.
  • EventSource lets you call disconnect() whenever you want.
  • EventSource doesn't store the Last-Event-Id anymore and you will have to take care of storing the id and sending using it or not in the connect method.
  • EventSource doesn't reconnect at all. If a network layer error occurs (disconnection, timeout, etc) or if the server closes the connection you will have to take care to reconnect with the server.
  • Modularization. This library has been around since Swift 1.0 and started just as a way to learn the language. With this new version the whole code has been improved, commented and fully tested to make it easier to track problems and extend in the future.

How to use it?

There is a simple working sample in the repository. Check the ViewController.swift to see how to use it.

Also in sse-server folder you will find an extremely simple node.js server to test the library. To run the server you just need to:

  • npm install
  • node sse.js

Install

Cocoapods

  1. Include EventSource in your Podfile: pod 'IKEventSource'

  2. Import the framework:

import IKEventSource

Carthage

  1. Include EventSource in your Cartfile: github "inaka/EventSource"

  2. Import the framework:

import IKEventSource

For further reference see Carthage's documentation.

Swift Package Manager

  1. Include EventSource in your Package.swift: github "inaka/EventSource"
import PackageDescription

let package = Package(
dependencies: [
    .package(url: "https://github.com/inaka/EventSource.git", .branch("master"))
])
  1. Import the framework:
import IKEventSource

Swift API:

/// RetryTime: This can be changed remotly if the server sends an event `retry:`
var retryTime: Int { get }

/// URL where EventSource will listen for events.
var url: URL { get }

/// The last event id received from server. This id is neccesary to keep track of the last event-id received to avoid
/// receiving duplicate events after a reconnection.
var lastEventId: String? { get }

/// Current state of EventSource
var readyState: EventSourceState { get }

/// Method used to connect to server. It can receive an optional lastEventId indicating the Last-Event-ID
///
/// - Parameter lastEventId: optional value that is going to be added on the request header to server.
func connect(lastEventId: String?)

/// Method used to disconnect from server.
func disconnect()

/// Returns the list of event names that we are currently listening for.
///
/// - Returns: List of event names.
func events() -> [String]

/// Callback called when EventSource has successfully connected to the server.
///
/// - Parameter onOpenCallback: callback
func onOpen(_ onOpenCallback: @escaping (() -> Void))

/// Callback called once EventSource has disconnected from server. This can happen for multiple reasons.
/// The server could have requested the disconnection or maybe a network layer error, wrong URL or any other
/// error. The callback receives as parameters the status code of the disconnection, if we should reconnect or not
/// following event source rules and finally the network layer error if any. All this information is more than
/// enought for you to take a decition if you should reconnect or not.
/// - Parameter onOpenCallback: callback
func onComplete(_ onComplete: @escaping ((Int?, Bool?, NSError?) -> Void))

/// This callback is called everytime an event with name "message" or no name is received.
func onMessage(_ onMessageCallback: @escaping ((_ id: String?, _ event: String?, _ data: String?) -> Void))

/// Add an event handler for an specific event name.
///
/// - Parameters:
///   - event: name of the event to receive
///   - handler: this handler will be called everytime an event is received with this event-name
func addEventListener(_ event: String,
                      handler: @escaping ((_ id: String?, _ event: String?, _ data: String?) -> Void))

/// Remove an event handler for the event-name
///
/// - Parameter event: name of the listener to be remove from event source.
func removeEventListener(_ event: String)

Examples:


Event:

id: event-id
event: event-name
data: event-data

Calls

eventSource.addEventListener("event-name") { (id, event, data) in
  // Here you get an event 'event-name'
}

Event:

id: event-id
data: event-data
data: event-data

Calls

eventSource.onMessage { (id, event, data) in
  // Here you get an event without event name!
}

Event:

id: event-id
data: event-data-1
data: event-data-2
data: event-data-3

Calls

eventSource.onMessage { (id, event, data) in
  // Here you get an event without event name!
  // data: event-data-1\nevent-data-2\nevent-data-3
}

Event:

:heartbeat

Calls

nothing it's a comment

Live example

This is the example shipped with the app. If you run the server and run the app you will be able to see this example live. The moving box is just to show that everything works on background and the main thread performance shows no degradation. (The gif is pretty bad to see that, but if you click on the image you will be taken to the gfycat version of the gif which runs way smoother)

Sample

Contributors

Thanks to all the contributors for pointing out missing stuff or problems and fixing them or opening issues!!

Contact Us

If you find any bugs or have a problem while using this library, please open an issue in this repo (or a pull request :)).

Please provide an example of the problem you are facing. If an event is not correctly parsed please provide a sample event.

More Repositories

1

erlang_guidelines

Inaka's Erlang Coding Guidelines
Erlang
619
star
2

galgo

When you want your logs to be displayed on screen
Java
427
star
3

elvis

Erlang Style Reviewer
Erlang
424
star
4

apns4erl

Apple Push Notification Server for Erlang
Erlang
369
star
5

TinyTask

A Tiny Task Library
Java
324
star
6

worker_pool

Erlang worker pool
Erlang
274
star
7

sumo_db

Erlang Persistency Framework
Erlang
173
star
8

shotgun

For the times you need more than just a gun.
Erlang
166
star
9

Dayron

A repository `similar` to Ecto.Repo that maps to an underlying http client, sending requests to an external rest api instead of a database
Elixir
159
star
10

cowboy_swagger

Swagger integration for Cowboy (built on trails)
Erlang
120
star
11

gold_fever

A Treasure Hunt for Erlangers
Erlang
86
star
12

Jayme

Abstraction layer that eases RESTful interconnections in Swift
Swift
81
star
13

guidelines

General Inaka Guidelines
75
star
14

cowboy-trails

A couple of improvements over Cowboy Routes
Erlang
71
star
15

jem.js

Just Erlang Maps for Javascript
JavaScript
69
star
16

sheldon

Very Simple Erlang Spell Checker
Erlang
62
star
17

elvis_core

The core of an Erlang linter
Erlang
61
star
18

niffy

Inline C code in Erlang modules to build NIFs
Erlang
60
star
19

sumo_rest

Generic cowboy handlers to work with Sumo
Erlang
59
star
20

serpents

Multi-Player Game on top of HDP protocol
Erlang
56
star
21

xref_runner

Erlang Xref Runner (inspired in rebar xref)
Erlang
50
star
22

erlang-github

Github API client
Erlang
46
star
23

lasse

SSE handler for Cowboy
Erlang
45
star
24

beam_olympics

Let's find the fastest beamer!
Erlang
39
star
25

fiar

Four in a Row - A game to learn Erlang
Erlang
36
star
26

zipper

Generic Zipper implementation in Erlang
Erlang
34
star
27

ios-xmpp-sample

Blog post sample project.
Swift
33
star
28

kotlillon

Android Kotlin Examples
Kotlin
33
star
29

katana-test

Meta Testing Utilities for common_test
Erlang
32
star
30

match_stream

A sample project to show in our scale blog post
JavaScript
30
star
31

phoenix_passwordless_login

Phoenix Passwordless Login
Elixir
29
star
32

KillerTask

Android AsyncTask wrapper library, written in Kotlin
Kotlin
26
star
33

canillita

Simple Paperboy-themed PubSub
Erlang
26
star
34

lewis

Rock your Android
Java
22
star
35

tirerl

Erlang interface to Elastic Search
Erlang
19
star
36

itweet

Twitter Stream API on ibrowse
Erlang
18
star
37

katana-code

Code Utilities for Erlang
Erlang
17
star
38

pusherman

queuing system for push notifications
Erlang
17
star
39

galgo-ios

When you want your logs to be displayed on screen
Objective-C
16
star
40

lsl

NIM in Erlang
Erlang
15
star
41

credo_server

Credo Server
Elixir
15
star
42

FadeButton

Fading effects for UIButtons made simple
Swift
15
star
43

Jolly

Jolly Chimp that keeps track of our Github Repos
Swift
12
star
44

rpsls

Rock Paper Scissors Lizzard Spock World Championship in Erlang
Erlang
12
star
45

ikbot

An elixir based customizable hipchat bot
Elixir
12
star
46

nconf

Nested Configuration Manager for Erlang Applications
Erlang
12
star
47

pushito

APNS over HTTP/2
Elixir
11
star
48

rest_guidelines

REST API Design Guidelines
11
star
49

fetjaba

From Erlang To Java and Back Again
Erlang
9
star
50

sumo_db_pgsql

PostgreSQL adapter for sumo_db.
Erlang
9
star
51

jinterface_stdlib

Erlang stdlib implementation on Java, based on JInterface
Java
9
star
52

IKCapture

Snapchat-Like Image Capture Library
Objective-C
8
star
53

MediaPickerController

Neat API for presenting the classical action sheet for picking an image or video from the device or camera.
Swift
8
star
54

PictureViewMaster

Interactive image projector.
Swift
8
star
55

toy_kv

A simple and reduced Key-Value Store written in Erlang
Erlang
7
star
56

ColorPicker

Color Picker for Swift
Swift
7
star
57

swift_guidelines

Inaka's Swift Coding Guidelines
7
star
58

spellingci

Spelling CI Server
Erlang
7
star
59

talks

Sources and pdfs of our talks and speeches
TeX
6
star
60

bookmarks

A collection of bookmarks for Inakos
6
star
61

IKJayma

RESTful API abstraction for Server Interconnection
Objective-C
6
star
62

hexer

Hex.pm integration in escript format.
Erlang
6
star
63

hexer.mk

erlang.mk plugin for hexer
Makefile
5
star
64

android_guidelines

Inaka's Android Development Guidelines
5
star
65

elvis.mk

3rd party erlang.mk plug-in for Elvis
Shell
5
star
66

plixir

Poker + Elixir + Phoenix
CSS
5
star
67

ios_guidelines

Inaka's iOS Coding Guidelines
Objective-C
4
star
68

sumo_db_elasticsearch

ElasticSearch adapter for sumo_db
Erlang
4
star
69

tele_sign

Node.js library to send messages through http://www.telesign.com/
JavaScript
4
star
70

inaka.github.io

Inaka's Open Source Projects
HTML
3
star
71

sumo_db_riak

Riak adapter for sumo_db
Erlang
3
star
72

android-excercises

Quick test for Android candidates
3
star
73

sumo_db_mongo

MongoDB adapter for sumo_db
Erlang
2
star
74

Otec

A swift app to showcase our best open-source libraries
Swift
2
star
75

gold_fever-solver

A solver for the http://github.com/inaka/gold_fever game
Erlang
2
star
76

inaka.mk

erlang.mk extras that we generally use in all of our projects
Makefile
2
star
77

g2x

Graffle to XCode
Objective-C
2
star
78

beam_olympics-extended

Internal repo to keep secret beam_olympics tasks from the public view
Erlang
2
star
79

beam_olympics-solver

Solutions for beam_olympics
Elixir
2
star
80

emarkdown

Based on https://github.com/devinus/markdown - but for Erlang :)
C
2
star
81

sumo_db_mysql

MySQL adapter for sumo_db
Erlang
2
star
82

ruby_guidelines

Our own guidelines when it comes to ruby development
1
star
83

pokedex

Dumb repo to prove what we can do with sumo{_db|rest_}
Erlang
1
star
84

homebrew-formulas

Homebrew formulas for some of our tools
Ruby
1
star
85

updike

Run, rabbit, run
1
star
86

ios-scripts

Helper scripts that you can use in your iOS apps
Shell
1
star
87

INSocketListener

SSE Socket Listener for Objective-C
Objective-C
1
star