Server-sent event event source API client in ObjC for iOS and Mac using NSURLSession

TRVSEventSource provides an api for opening an http connection for receiving push notifications from a server in the form of server-sent events. Mozilla Developer Network has a good page on server-sent events and event source usage too.


TRVSEventSource *eventSource = [[TRVSEventSource alloc] initWithURL:[NSURL URLWithString:@""]];

[eventSource addListenerForEvent:@"message" usingEventHandler:^(TRVSServerSentEvent *event, NSError *error) {
    NSDictionary *JSON = [NSJSONSerialization options:0 error:NULL];
    Message *message = [Message messageWithJSON:JSON];
    NSArray *messages = [self.messages arrayByAddingObject:message];
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:messages.count inSection:0];

    dispatch_async(dispatch_get_main_queue(), ^{
        self.messages = messages;
        [self.collectionView insertItemsAtIndexPaths:@[indexPath]];

I wrote a test server that you can run during development too.

node ./TRVSEventSourceExample/server.js

❯ curl
event: message
data: {"id": 1, "body":"1381466575460", "author_id": 1, "conversation_id": 1}

event: message
data: {"id": 2, "body":"1381466577463", "author_id": 1, "conversation_id": 1}