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.

usage

TRVSEventSource *eventSource = [[TRVSEventSource alloc] initWithURL:[NSURL URLWithString:@"http://127.0.0.1:8000"]];

[eventSource addListenerForEvent:@"message" usingEventHandler:^(TRVSServerSentEvent *event, NSError *error) {
    NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:event.data 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 127.0.0.1:8000
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}

Follow me on Twitter to keep up with what I’ve learned building my personal finance tool, Stash.

Subscribe to my mailing list to learn more about technology and business.

Your email will never be shared with anyone else.

Read more posts …
Written: October 12th, 2013
Categories: ios, mac, objc, server-sent-event, eventsource, api, client, nsurlsession, html5, http