Skip to content

Instantly share code, notes, and snippets.

@scalabl3
Last active August 29, 2015 14:02
Show Gist options
  • Save scalabl3/e736706b1b38e510fa14 to your computer and use it in GitHub Desktop.
Save scalabl3/e736706b1b38e510fa14 to your computer and use it in GitHub Desktop.
PubNub Objective-C Subscribe to Channel and Add Receive Observer
// Message Receive Event for All Subscribed Channels
- (void)pubnubClient:(PubNub *)client didReceiveMessage:(PNMessage *)msg
{
NSLog(@"Message Received:\n Channel:%@\n Message:%@", msg.channel.name, [msg message]);
}
- (void) subscribeToChannel:(NSString*)channelName
{
PNChannel* channel = [PNChannel channelWithName:channelName];
// Subscribe to the Channel, on Subscribe, Create Observer
[PubNub subscribeOnChannel:pnChannel withCompletionHandlingBlock:^(PNSubscriptionProcessState state, NSArray *a, PNError *e) {
switch(state) {
case PNSubscriptionProcessWillRestoreState:
break;
case PNSubscriptionProcessRestoredState:
break;
// Subscribe Completed & Succeeded
case PNSubscriptionProcessSubscribedState:
NSLog(@"Subscribed to \"%@\" channel... done!", channelName);
// Specific Channel Observer Pattern (Add Observer)
[[PNObservationCenter defaultCenter]
addMessageReceiveObserver:nil
withBlock:^(PNMessage * msg)
{
if ([msg.channel.name isEqualToString:channelName]) {
// Do Stuff with Message Here
NSLog(@"\"%@\" Received Message:\n Message:%@", msg.channel.name, [msg message]);
}
break;
// Subscribe Failed
case PNSubscriptionProcessNotSubscribedState:
NSLog(@"Subscribing to \"%@\" channel... error!", channelName);
break;
}
}];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment