libPusher now supports event triggering

23 April 2010 libPusher now supports event triggering

Authentication support was recently added to Pusher so I took the opportunity to add support to libPusher for triggering events using the Pusher REST API.

As part of my implementation, I've introduced a new, higher-level API in the form of PTPusherChannel. It sacrifices some flexibility (by using a shared API key, secret and app ID) for the sake of ease of use and attempts to mirror the way the Ruby Pusher client gem works. All of the lower-level API detailed in my original blog post is still available.

To use it, you first need to configure PTPusher with your credentials; a good place to do this is in your applicationDidFinishLaunching app delegate method:

- (void)applicationDidFinishLaunching:(UIApplication *)application 
{
  [PTPusher setKey:@"your api key"];
  [PTPusher setSecret:@"secret"];
  [PTPusher setAppID:@"app id"];
  ...
}

Once you have done this, creating new channels is easy:

myChannel = [[PTPusher channel:@"demo"] retain];

Note that the channel methods returns an autoreleased PTPusherChannel instance so you will need to retain it and release it when you are finished with it.

To trigger a new event, simply call the triggerEvent:data: method; the data parameter can be a string or any Objective-C object that can be serialized as JSON, such as an array or dictionary:

NSArray *objects = [NSArray arrayWithObjects:@"one", @"two", @"three", nil];
[myChannel triggerEvent:@"demo-event" data:objects];

In addition to being able to trigger events, PTPusherChannel offers an alternative means of receiving events on that channel using a delegate:

- (void)viewDidLoad;
{
  ...
  myChannel.delegate = self;
}

- (void)channel:(PTPusherChannel *)channel didReceiveEvent:(PTPusherEvent *)event;
{
  // handle event
}

Here is a small screencast of the included sample app triggering and handling its own events.

For more details, check out the updated README on GitHub and take a look at the sample app.