Publish/Subscribe API for PubNub Objective-C SDK

The foundation of the PubNub service is the ability to send a message and have it delivered anywhere in less than 100ms. Send a message to just one other person, or broadcast to thousands of subscribers at once.

For higher-level conceptual details on publishing and subscribing, refer to Connection Management and to Publish Messages.

Publish

publish() sends a message to all channel subscribers. A successfully published message is replicated across PubNub's points of presence and sent simultaneously to all subscribed clients on a channel.

ObjectNode

The new Jackson parser does not recognize JSONObject. Use ObjectNode instead.

  • You must initialize PubNub with the publishKey.
  • You don't have to be subscribed to a channel to publish to it.
  • You cannot publish to multiple channels simultaneously.

Method(s)

To Publish a message you can use the following method(s) in the Objective-C SDK:

Publish a message with block

- (void)publish:(id)message 
toChannel:(NSString *)channel
withCompletion:(nullable PNPublishCompletionBlock)block;
ParameterTypeRequiredDescription
messageidYesReference on Foundation object ( NSString, NSNumber, NSArray, NSDictionary) which will be published.
channelNSStringYesReference on name of the channel to which message should be published.
blockPNPublishCompletionBlockNoPublish processing completion block which pass only one argument - request processing status to report about how data pushing was successful or not.

Publish a message with compression and block

- (void)publish:(id)message 
toChannel:(NSString *)channel
compressed:(BOOL)compressed
withCompletion:(nullable PNPublishCompletionBlock)block;
ParameterTypeRequiredDescription
messageidYesReference on Foundation object (NSString, NSNumber, NSArray, NSDictionary) which will be published.
channelNSStringYesReference on name of the channel to which message should be published.
compressedBOOLYesWhether message should be compressed and sent with request body instead of URI part. Compression useful in case if large data should be published, in another case it will lead to packet size grow.
blockPNPublishCompletionBlockNoPublish processing completion block which pass only one argument - request processing status to report about how data pushing was successful or not.

Publish a message with storage and block

- (void)publish:(id)message 
toChannel:(NSString *)channel
storeInHistory:(BOOL)shouldStore
withCompletion:(nullable PNPublishCompletionBlock)block;
ParameterTypeRequiredDescription
messageidYesReference on Foundation object (NSString, NSNumber, NSArray,NSDictionary) which will be published.
channelNSStringYesReference on name of the channel to which message should be published.
shouldStoreBOOLYesWith NO this message later won't be fetched using Message Persistence API.
blockPNPublishCompletionBlockNoPublish processing completion block which pass only one argument - request processing status to report about how data pushing was successful or not.

Publish a message with storage, compression, and block

- (void)publish:(id)message 
toChannel:(NSString *)channel
storeInHistory:(BOOL)shouldStore
compressed:(BOOL)compressed
withCompletion:(nullable PNPublishCompletionBlock)block;
ParameterTypeRequiredDescription
messageidYesReference on Foundation object (NSString, NSNumber, NSArray,NSDictionary) which will be published.
channelNSStringYesReference on name of the channel to which message should be published.
shouldStoreBOOLYesWith NO this message later won't be fetched using Message Persistence API.
compressedBOOLYesCompression useful in case if large data should be published, in another case it will lead to packet size grow.
blockPNPublishCompletionBlockNoPublish processing completion block which pass only one argument - request processing status to report about how data pushing was successful or not.

Publish a message with payload and block

- (void)publish:(nullable id)message 
toChannel:(NSString *)channel
mobilePushPayload:(nullable NSDictionary<NSString *, id> *)payloads
withCompletion:(nullable PNPublishCompletionBlock)block;
ParameterTypeRequiredDescription
messageidNoReference on Foundation object (NSString, NSNumber, NSArray, NSDictionary) which will be published.
channelNSStringYesReference on name of the channel to which message should be published.
payloadsNSDictionaryNoDictionary with payloads for different vendors (Apple with apns key and Google with gcm).
blockPNPublishCompletionBlockNoPublish processing completion block which pass only one argument - request processing status to report about how data pushing was successful or not.

Publish a message with payload, compression, and block

- (void)publish:(nullable id)message 
toChannel:(NSString *)channel
mobilePushPayload:(nullable NSDictionary<NSString *, id> *)payloads
compressed:(BOOL)compressed
withCompletion:(nullable PNPublishCompletionBlock)block;
ParameterTypeRequiredDescription
messageidNoReference on Foundation object (NSString, NSNumber, NSArray, NSDictionary) which will be published.
channelNSStringYesReference on name of the channel to which message should be published.
payloadsNSDictionaryYesDictionary with payloads for different vendors (Apple with apns key and Google with gcm).
compressedBOOLYesCompression useful in case if large data should be published, in another case it will lead to packet size grow.
blockPNPublishCompletionBlockNoPublish processing completion block which pass only one argument - request processing status to report about how data pushing was successful or not.

Publish a message with payload, storage, and block

- (void)publish:(nullable id)message 
toChannel:(NSString *)channel
mobilePushPayload:(nullable NSDictionary<NSString *, id> *)payloads
storeInHistory:(BOOL)shouldStore
withCompletion:(nullable PNPublishCompletionBlock)block;
ParameterTypeRequiredDescription
messageidNoReference on Foundation object (NSString, NSNumber, NSArray,NSDictionary) which will be published.
channelNSStringYesReference on name of the channel to which message should be published.
payloadsNSDictionaryNoDictionary with payloads for different vendors (Apple with apns key and Google with gcm).
shouldStoreBOOLYesWith NO this message later won't be fetched using Message Persistence API.
blockPNPublishCompletionBlockNoPublish processing completion block which pass only one argument - request processing status to report about how data pushing was successful or not.

Publish a message with payloads, storage, compression, and block

- (void)publish:(nullable id)message 
toChannel:(NSString *)channel
mobilePushPayload:(nullable NSDictionary<NSString *, id> *)payloads
storeInHistory:(BOOL)shouldStore
compressed:(BOOL)compressed
withCompletion:(nullable PNPublishCompletionBlock)block;
ParameterTypeRequiredDescription
messageidNoReference on Foundation object (NSString, NSNumber, NSArray,NSDictionary) which will be published.
channelNSStringYesReference on name of the channel to which message should be published.
payloadsNSDictionaryNoDictionary with payloads for different vendors (Apple with "apns" key and Google with "gcm").
shouldStoreBOOLYesWith NO this message later won't be fetched using Message Persistence API.
compressedBOOLYesCompression useful in case if large data should be published, in another case it will lead to packet size grow.
blockPNPublishCompletionBlockNoPublish processing completion block which pass only one argument - request processing status to report about how data pushing was successful or not.

Publish a message with metadata and block

- (void)publish:(id)message 
toChannel:(NSString *)channel
withMetadata:(nullable NSDictionary<NSString *, id> *)metadata
completion:(nullable PNPublishCompletionBlock)block;
ParameterTypeRequiredDescription
messageidYesThe message may be any valid foundation object (String, NSNumber, Array, Dictionary).
channelNSStringYesSpecifies channel name to publish messages to.
metadataNSDictionaryNoNSDictionary with values which should be used by PubNub service to filter messages.
blockPNPublishCompletionBlockNoThe completion block which will be called when the processing is complete, has one argument: - request status reports the publish was successful or not (errorData contains error information in case of failure).

Publish a message with compression, metadata, and block

- (void)publish:(id)message 
toChannel:(NSString *)channel
compressed:(BOOL)compressed
withMetadata:(nullable NSDictionary<NSString *, id> *)metadata
completion:(nullable PNPublishCompletionBlock)block;
ParameterTypeRequiredDescription
messageidYesThe message may be any valid foundation object (String, NSNumber, Array, Dictionary).
channelNSStringYesSpecifies channel name to publish messages to.
compressedBOOLYesIf true the message will be compressed and sent with request body instead of the URI. Compression useful in case of large data, in another cases it will increase the packet size.
metadataNSDictionaryNoNSDictionary with values which should be used by PubNub service to filter messages.
blockPNPublishCompletionBlockNoThe completion block which will be called when the processing is complete, has one argument: - request status reports the publish was successful or not (errorData contains error information in case of failure).

Publish a message with storage, metadata, and block

- (void)publish:(id)message 
toChannel:(NSString *)channel
storeInHistory:(BOOL)shouldStore
withMetadata:(nullable NSDictionary<NSString *, id> *)metadata
completion:(nullable PNPublishCompletionBlock)block;
ParameterTypeRequiredDescription
messageidYesThe message may be any valid foundation object (String, NSNumber, Array, Dictionary).
channelNSStringYesSpecifies channel name to publish messages to.
shouldStoreBOOLYesIf false the messages will not be stored in Message Persistence, default true.
metadataNSDictionaryNoNSDictionary with values which should be used by PubNub service to filter messages.
blockPNPublishCompletionBlockNoThe completion block which will be called when the processing is complete, has one argument: - request status reports the publish was successful or not (errorData contains error information in case of failure).

Publish a message with storage, compression, metadata, and block

- (void)publish:(id)message 
toChannel:(NSString *)channel
storeInHistory:(BOOL)shouldStore
compressed:(BOOL)compressed
withMetadata:(nullable NSDictionary<NSString *, id> *)metadata
completion:(nullable PNPublishCompletionBlock)block;
ParameterTypeRequiredDescription
messageidYesThe message may be any valid foundation object (String, NSNumber, Array, Dictionary).
channelNSStringYesSpecifies channel name to publish messages to.
shouldStoreBOOLYesIf false the messages will not be stored in Message Persistence, default true.
compressedBOOLYesIf true the message will be compressed and sent with request body instead of the URI. Compression useful in case of large data, in another cases it will increase the packet size.
metadataNSDictionaryNoNSDictionary with values which should be used by PubNub service to filter messages.
blockPNPublishCompletionBlockNoThe completion block which will be called when the processing is complete, has one argument: - request status reports the publish was successful or not (errorData contains error information in case of failure).

Publish a message with payload, metadata, and block

- (void)publish:(nullable id)message 
toChannel:(NSString *)channel
mobilePushPayload:(nullable NSDictionary<NSString *, id> *)payloads
withMetadata:(nullable NSDictionary<NSString *, id> *)metadata
completion:(nullable PNPublishCompletionBlock)block;
ParameterTypeRequiredDescription
messageidNoThe message may be any valid foundation object (String, NSNumber, Array, Dictionary).
channelNSStringYesSpecifies channel name to publish messages to.
payloadsNSDictionaryNoDictionary with payloads for different vendors (Apple with aps key and Google with gcm). Either payloads or message should be provided..
metadataNSDictionaryNoNSDictionary with values which should be used by PubNub service to filter messages.
blockPNPublishCompletionBlockNoThe completion block which will be called when the processing is complete, has one argument: - request status reports the publish was successful or not (errorData contains error information in case of failure).

Publish a message with payload, compression, metadata, and block

- (void)publish:(nullable id)message 
toChannel:(NSString *)channel
mobilePushPayload:(nullable NSDictionary<NSString *, id> *)payloads
compressed:(BOOL)compressed
withMetadata:(nullable NSDictionary<NSString *, id> *)metadata
completion:(nullable PNPublishCompletionBlock)block;
ParameterTypeRequiredDescription
messageidNoThe message may be any valid foundation object (String, NSNumber, Array, Dictionary).
channelNSStringYesSpecifies channel name to publish messages to.
payloadsNSDictionaryNoDictionary with payloads for different vendors (Apple with aps key and Google with gcm). Either payloads or message should be provided.
compressedBOOLYesIf true the message will be compressed and sent with request body instead of the URI. Compression useful in case of large data, in another cases it will increase the packet size.
metadataNSDictionaryNoNSDictionary with values which should be used by PubNub service to filter messages.
blockPNPublishCompletionBlockNoThe completion block which will be called when the processing is complete, has one argument: - request status reports the publish was successful or not (errorData contains error information in case of failure).

Publish a message with payload, storage, metadata, and block

- (void)publish:(nullable id)message 
toChannel:(NSString *)channel
mobilePushPayload:(nullable NSDictionary<NSString *, id> *)payloads
storeInHistory:(BOOL)shouldStore
withMetadata:(nullable NSDictionary<NSString *, id> *)metadata
completion:(nullable PNPublishCompletionBlock)block;
ParameterTypeRequiredDescription
messageidNoThe message may be any valid foundation object (String, NSNumber, Array, Dictionary).
channelNSStringYesSpecifies channel name to publish messages to.
payloadsNSDictionaryNoDictionary with payloads for different vendors (Apple with a ps key and Google with gcm). Either payloads or message should be provided.
shouldStoreBOOLYesIf false the messages will not be stored in Message Persistence, default true.
metadataNSDictionaryNoNSDictionary with values which should be used by PubNub service to filter messages.
blockPNPublishCompletionBlockNoThe completion block which will be called when the processing is complete, has one argument: - request status reports the publish was successful or not (errorData contains error information in case of failure).

Publish a message with payload, storage, compression, metadata, and block

- (void)publish:(nullable id)message 
toChannel:(NSString *)channel
mobilePushPayload:(nullable NSDictionary<NSString *, id> *)payloads
storeInHistory:(BOOL)shouldStore
compressed:(BOOL)compressed
withMetadata:(nullable NSDictionary<NSString *, id> *)metadata
completion:(nullable PNPublishCompletionBlock)block;
ParameterTypeRequiredDescription
messageidNoThe message may be any valid foundation object (String, NSNumber, Array, Dictionary).
channelNSStringYesSpecifies channel name to publish messages to.
payloadsNSDictionaryNoDictionary with payloads for different vendors (Apple with aps key and Google with gcm). Either payloads or message should be provided.
shouldStoreBOOLYesIf false the messages will not be stored in Message Persistence, default true.
compressedBOOLYesIf true the message will be compressed and sent with request body instead of the URI. Compression useful in case of large data, in another cases it will increase the packet size.
metadataNSDictionaryNoNSDictionary with values which should be used by PubNub service to filter messages.
blockPNPublishCompletionBlockNoThe completion block which will be called when the processing is complete, has one argument: - request status reports the publish was successful or not (errorData contains error information in case of failure).

Basic Usage

Publish a message to a channel

[self.client publish: @{@"Dictionary": @[@"with",@"array",@"as", @"value"]}
toChannel: @"pubnub" withCompletion:^(PNPublishStatus *status) {

if (!status.isError) {

// Message successfully published to specified channel.
}
else {

/**
Handle message publish error. Check 'category' property to find
out possible reason because of which request did fail.
Review 'errorData' property (which has PNErrorData data type) of status
object to get additional information about issue.

show all 19 lines
Subscribe to the channel

Before running the above publish example, either using the Debug Console or in a separate script running in a separate terminal window, subscribe to the same channel that is being published to.

Response

Response objects which is returned by client when publish API is used:

@interface PNPublishData : PNServiceData

@property (nonatomic, readonly, strong) NSNumber *timetoken;
@property (nonatomic, readonly, strong) NSString *information;

@end

@interface PNPublishStatus : PNAcknowledgmentStatus

@property (nonatomic, readonly, strong) PNPublishData *data;

@end

Other Examples

Publish with metadata

[self publish: @"Hello from the PubNub Objective-C" toChannel:@"chat_channel"
withMetadata: @{@"senderID" : @"bob"} completion:^(PNPublishStatus *status) {

if (!status.isError) {

// Message successfully published to specified channel.
}
else {

/**
Handle message publish error. Check 'category' property to find
out possible reason because of which request did fail.
Review 'errorData' property (which has PNErrorData data type) of status
object to get additional information about issue.

show all 19 lines

Push Payload Helper

You can use the helper method as an input to the Message parameter, to format the payload for publishing Push messages. For more info on the helper method, check Create Push Payload Helper Section

Publish (Builder Pattern)

This function publishes a message on a channel.

Note

This method uses the builder pattern, you can remove the args which are optional.

Method(s)

To run Publish Builder you can use the following method(s) in the Objective-C SDK:

publish()
.message(id)
.channel(NSString *)
.shouldStore(BOOL)
.compress(BOOL)
.ttl(NSUInteger)
.payloads(NSDictionary *)
.metadata(NSDictionary *)
.customMessageType(NSString*)
.performWithCompletion(PNPublishCompletionBlock);
ParameterTypeRequiredDescription
messageidNoThe message may be any valid foundation object (NSString, NSNumber, NSArray, NSDictionary).
channelNSString*YesSpecifies channel name to publish messages to.
shouldStoreBOOLNoIf NO the messages will not be stored in history.
Default YES.
compressBOOLNoIf YES the message will be compressed and sent with request body instead of the URI. Compression useful in case of large data, in another cases it will increase the packet size.
ttlNSUIntegerNoSpecify for how many hours published message should be stored.
payloadsNSDictionaryNoDictionary with payloads for different vendors (Apple with aps key and Google with gcm). Either payloads or message should be provided.
metadataNSDictionaryNoNSDictionary with values which should be used by PubNub service to filter messages.
customMessageTypeNSString*OptionalA case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes - and underscores _ are allowed. The value cannot start with special characters or the string pn_ or pn-.

Examples: text, action, poll.
blockPNPublishCompletionBlockNoThe completion block which will be called when the processing is complete, has one argument: - request status reports the publish was successful or not (errorData contains error information in case of failure).

Basic Usage

Publish message which will be stored in Message Persistence for next 16 hours.

self.client.publish()
.channel(@"my_channel")
.message(@"Hello from PubNub iOS!")
.shouldStore(YES)
.ttl(16)
.customMessageType(@"text-message")
.performWithCompletion(^(PNPublishStatus *status) {

if (!status.isError) {

// Message successfully published to specified channel.
}
else {

/**
show all 24 lines

Fire (Builder Pattern)

The fire endpoint allows the client to send a message to BLOCKS Event Handlers. These messages will go directly to any Event Handlers registered on the channel that you fire to and will trigger their execution. The content of the fired request will be available for processing within the Event Handler. The message sent via fire() is not replicated, and so will not be received by any subscribers to the channel. The message is also not stored in history.

Note

This method uses the builder pattern, you can remove the args which are optional.

Method(s)

To Fire a message you can use the following method(s) in the Objective-C SDK:

fire()
.message(id)
.channel(NSString *)
.compress(BOOL)
.payloads(NSDictionary *)
.metadata(NSDictionary *)
.performWithCompletion(PNPublishCompletionBlock);
ParameterTypeRequiredDescription
messageidNoThe message may be any valid foundation object (NSString, NSNumber, NSArray, NSDictionary).
channelNSStringYesSpecifies channel name to publish messages to.
compressBOOLNoIf YES the message will be compressed and sent with request body instead of the URI. Compression useful in case of large data, in another cases it will increase the packet size.
payloadsNSDictionaryNoDictionary with payloads for different vendors (Apple with aps key and Google with gcm). Either payloads or message should be provided.
metadataNSDictionaryNoNSDictionary with values which should be used by PubNub service to filter messages.
blockPNPublishCompletionBlockNoThe completion block which will be called when the processing is complete, has one argument: - request status reports the publish was successful or not (errorData contains error information in case of failure).

Basic Usage

self.client.fire()
.channel(@"my_channel")
.message(@"Hello from PubNub iOS!")
.shouldStore(YES)
.performWithCompletion(^(PNPublishStatus *status) {

if (!status.isError) {

// Message successfully published to specified channel.
}
else {

/**
Handle message publish error. Check 'category' property to find
out possible reason because of which request did fail.
show all 22 lines

Signal

The signal() function is used to send a signal to all subscribers of a channel.

By default, signals are limited to a message payload size of 64 bytes. This limit applies only to the payload, and not to the URI or headers. If you require a larger payload size, please contact support.

Method(s)

To Signal a message you can use the following method(s) in the Objective-C SDK:

- (void)signal:(id)message 
channel:(NSString *)channel
withCompletion:(nullable PNSignalCompletionBlock)block;
ParameterTypeRequiredDescription
messageidYesObject (NSString, NSNumber, NSArray, NSDictionary) which will be sent with signal.
channelNSStringYesName of the channel to which signal should be sent.
blockPNSignalCompletionBlockNoSignal processing completion block which pass only one argument - request processing status to report about how data pushing was successful or not.

Basic Usage

Signal a message to a channel

[self.client signal:@{ @"Hello": @"world" } channel:@"announcement"
withCompletion:^(PNSignalStatus *status) {

if (!status.isError) {
// Signal successfully sent to specified channel.
} else {
/**
* Handle signal sending error. Check 'category' property to find out possible issue
* because of which request did fail.
*
* Request can be resent using: [status retry];
*/
}
}];

Response

Response objects returned by the client when Signal API is used:

@interface PNSignalStatusData : PNServiceData

@property (nonatomic, readonly, strong) NSNumber *timetoken;
@property (nonatomic, readonly, strong) NSString *information;

@end

@interface PNSignalStatus : PNAcknowledgmentStatus

@property (nonatomic, readonly, strong) PNSignalStatusData *data;

@end

Signal (Builder Pattern)

Note

This method uses the builder pattern, you can remove the args which are optional.

Method(s)

To run Signal Builder you can use the following method(s) in the Objective-C SDK:

signal()
.message(id)
.channel(NSString *)
.customMessageType(NSString *)
.performWithCompletion(PNSignalCompletionBlock);
ParameterTypeRequiredDescription
messageArrayYesObject (NSString, NSNumber, NSArray, NSDictionary) which will be sent with signal.
channelStringYesName of the channel to which signal should be sent.
customMessageTypeNSString*OptionalA case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes - and underscores _ are allowed. The value cannot start with special characters or the string pn_ or pn-.

Examples: text, action, poll.
blockPNSignalCompletionBlockNoSignal processing completion block which pass only one argument - request processing status to report about how data pushing was successful or not.

Basic Usage

Signal a message to a channel

self.client.signal().message(@{ @"Hello": @"world" }).channel(@"announcement").customMessageType(@"text-message-signal").performWithCompletion(^(PNSignalStatus *status) {

if (!status.isError) {
// Signal successfully sent to specified channel.
} else {
/**
* Handle signal sending error. Check 'category' property to find out possible issue
* because of which request did fail.
*
* Request can be resent using: [status retry];
*/
}
});
Response

Response objects which is returned by client when Signal API is used::

@interface PNSignalStatusData : PNServiceData

@property (nonatomic, readonly, strong) NSNumber *timetoken;
@property (nonatomic, readonly, strong) NSString *information;

@end

@interface PNSignalStatus : PNAcknowledgmentStatus

@property (nonatomic, readonly, strong) PNSignalStatusData *data;

@end

Subscribe

Receive messages

Your app receives messages and events via event listeners. The event listener is a single point through which your app receives all the messages, signals, and events that are sent in any channel you are subscribed to.

For more information about adding a listener, refer to the Event Listeners section.

Description

This function causes the client to create an open TCP socket to the PubNub Real-Time Network and begin listening for messages on a specified channel. To subscribe to a channel the client must send the appropriate subscribeKey at initialization. By default a newly subscribed client will only receive messages published to the channel after the subscribeToChannels call completes.

Connectivity notification

You can be notified of connectivity via the connect callback. By waiting for the connect callback to return before attempting to publish, you can avoid a potential race condition on clients that subscribe and immediately publish messages before the subscribe has completed.

Using Objective-C SDK, if a client becomes disconnected from a channel, it can automatically attempt to reconnect to that channel and retrieve any available messages that were missed during that period by setting restore to YES. By default a client will attempt to reconnect after exceeding a 320 second connection timeout.

Unsubscribing from all channels

Unsubscribing from all channels, and then subscribing to a new channel Y is not the same as subscribing to channel Y and then unsubscribing from the previously-subscribed channel(s). Unsubscribing from all channels resets the last-received timetoken and thus, there could be some gaps in the subscription that may lead to message loss.

Method(s)

To Subscribe to a channel you can use the following method(s) in the Objective-C SDK:

- (void)subscribeToChannels:(NSArray<NSString *> *)channels 
withPresence:(BOOL)shouldObservePresence;
ParameterTypeRequiredDescription
channelsNSArrayYesList of channel names on which client should try to subscribe.
shouldObservePresenceBOOLYesWhether presence observation should be enabled for channels or not.
- (void)subscribeToChannels:(NSArray<NSString *> *)channels 
withPresence:(BOOL)shouldObservePresence
clientState:(nullable NSDictionary<NSString *, id> *)state;
ParameterTypeRequiredDescription
channelsNSArrayYesList of channel names on which client should try to subscribe.
shouldObservePresenceBOOLYesWhether presence observation should be enabled for channels or not.
stateNSDictionaryNoReference on dictionary which stores key-value pairs based on channel name and value which should be assigned to it.
- (void)subscribeToChannels:(NSArray<NSString *> *)channels 
withPresence:(BOOL)shouldObservePresence
usingTimeToken:(nullable NSNumber *)timeToken;
ParameterTypeRequiredDescription
channelsNSArrayYesList of channel names on which client should try to subscribe.
shouldObservePresenceBOOLYesWhether presence observation should be enabled for channels or not.
timeTokenNSNumberNoSpecifies time from which to start returning any available cached messages. Message retrieval with timetoken is not guaranteed and should only be considered a best-effort service.
- (void)subscribeToChannels:(NSArray<NSString *> *)channels 
withPresence:(BOOL)shouldObservePresence
usingTimeToken:(nullable NSNumber *)timeToken
clientState:(nullable NSDictionary<NSString *, id> *)state;
ParameterTypeRequiredDescription
channelsNSArrayYesList of channel names on which client should try to subscribe.
shouldObservePresenceBOOLYesWhether presence observation should be enabled for channels or not.
timeTokenNSNumberNoSpecifies time from which to start returning any available cached messages. Message retrieval with timetoken is not guaranteed and should only be considered a best-effort service.
stateNSDictionaryNoReference on dictionary which stores key-value pairs based on channel name and value which should be assigned to it.

Basic Usage

Subscribe to a channel:

/**
Subscription results arrive to a listener which should implement the
PNObjectEventListener protocol and be registered as follows:
*/
[self.client addListener:self];
[self.client subscribeToChannels: @[@"my_channel1", @"my_channel2"] withPresence:NO];

// Handle a new message from a subscribed channel
- (void)client:(PubNub *)client didReceiveMessage:(PNMessageResult *)message {
// Reference to the channel group containing the chat the message was sent to
NSString *subscription = message.data.subscription;
NSLog(@"%@ sent message to '%@' at %@: %@", message.data.publisher, message.data.channel,
message.data.timetoken, message.data.message);
}

show all 97 lines

Response

@interface PNSubscriberData : PNServiceData

// Name of channel on which subscriber received data.
@property (nonatomic, readonly, strong) NSString *channel;

// Name of channel or channel group (if not equal to channel name).
@property (nonatomic, nullable, readonly, strong) NSString *subscription;

// Time at which the event arrived.
@property (nonatomic, readonly, strong) NSNumber *timetoken;

// Stores a reference to the metadata information passed along with the received event.
@property (nonatomic, nullable, readonly, strong) NSDictionary<NSString *, id> *userMetadata;

@end
show all 120 lines

Other Examples

Wildcard subscribe to channels

Requires Stream Controller add-on

This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal (with Enable Wildcard Subscribe checked). Read the support page on enabling add-on features on your keys.

Wildcard subscribes allow the client to subscribe to multiple channels using wildcard. For example, if you subscribe to a.* you will get all messages for a.b, a.c, a.x. The wildcarded * portion refers to any portion of the channel string name after the dot (.).

[self.client subscribeToChannels: @[@"my_channel.*"] withPresence:YES];
Wildcard grants and revokes

Only one level (a.*) of wildcarding is supported. If you grant on * or a.b.*, the grant will treat * or a.b.* as a single channel named either * or a.b.*. You can also revoke permissions from multiple channels using wildcards but only if you previously granted permissions using the same wildcards. Wildcard revokes, similarly to grants, only work one level deep, like a.*.

Subscribing to a Presence channel

Requires Presence add-on

This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

For any given channel there is an associated Presence channel. You can subscribe directly to the channel by appending -pnpres to the channel name. For example the channel named my_channel would have the presence channel named my_channel-pnpres.

/**
Subscription process results arrive to listener which should adopt to
PNObjectEventListener protocol and registered using:
*/
[self.client addListener:self];
[self.client subscribeToPresenceChannels:@[@"my_channel"]];

// New presence event handling.
- (void)client:(PubNub *)client didReceivePresenceEvent:(PNPresenceEventResult *)event {

if (![event.data.channel isEqualToString:event.data.subscription]) {

// Presence event has been received on channel group stored in event.data.subscription.
}
else {
show all 31 lines

Sample Responses

Join Event
{
"action": "join",
"timestamp": 1345546797,
"uuid": "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
"occupancy": 2
}
Leave Event
{
"action" : "leave",
"timestamp" : 1345549797,
"uuid" : "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
"occupancy" : 1
}
Timeout Event
{
"action": "timeout",
"timestamp": 1345549797,
"uuid": "76c2c571-9a2b-d074-b4f8-e93e09f49bd",
"occupancy": 0
}
Custom Presence Event (State Change)
{
"action": "state-change",
"uuid": "76c2c571-9a2b-d074-b4f8-e93e09f49bd",
"timestamp": 1345549797,
"data": {
"isTyping": true
}
}
Interval Event
{
"action":"interval",
"timestamp":1474396578,
"occupancy":2
}

When a channel is in interval mode with presence_deltas pnconfig flag enabled, the interval message may also include the following fields which contain an array of changed UUIDs since the last interval message.

  • joined
  • left
  • timedout

For example, this interval message indicates there were 2 new UUIDs that joined and 1 timed out UUID since the last interval:

{
"action" : "interval",
"occupancy" : <# users in channel>,
"timestamp" : <unix timestamp>,
"joined" : ["uuid2", "uuid3"],
"timedout" : ["uuid1"]
}

If the full interval message is greater than 30KB (since the max publish payload is ∼32KB), none of the extra fields will be present. Instead there will be a here_now_refresh boolean field set to true. This indicates to the user that they should do a hereNow request to get the complete list of users present in the channel.

{
"action" : "interval",
"occupancy" : <# users in channel>,
"timestamp" : <unix timestamp>,
"here_now_refresh" : true
}

Subscribing with State

Requires Presence add-on

This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

Required UUID

Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID, you won't be able to connect to PubNub.

// Initialize and configure PubNub client instance
PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:@"demo" subscribeKey:@"demo"];
configuration.uuid = @"myUniqueUUID";
self.client = [PubNub clientWithConfiguration:configuration];
[self.client addListener:self];

// Subscribe to demo channel with presence observation
[self.client subscribeToChannels: @[@"my_channel"] withPresence:YES];

- (void)client:(PubNub *)client didReceiveStatus:(PNStatus *)status {

if (status.category == PNConnectedCategory) {
[self.client setState: @{@"new": @"state"} forUUID:self.client.uuid onChannel: @"my_channel"
withCompletion:^(PNClientStateUpdateStatus *status) {

show all 47 lines

Subscribe Channel Group

Requires Stream Controller add-on

This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

This functions subscribes to a channel group.

Method(s)

To Subscribe to a Channel Group you can use the following method(s) in the Objective-C SDK:

- (void)subscribeToChannelGroups:(NSArray<NSString *> *)groups 
withPresence:(BOOL)shouldObservePresence;
ParameterTypeRequiredDescription
groupsNSArrayYesList of channel group names on which client should try to subscribe.
shouldObservePresenceBOOLYesWhether presence observation should be enabled for groups or not.
- (void)subscribeToChannelGroups:(NSArray<NSString *> *)groups 
withPresence:(BOOL)shouldObservePresence
clientState:(nullable NSDictionary<NSString *, id> *)state;
ParameterTypeRequiredDescription
groupsNSArrayYesList of channel group names on which client should try to subscribe.
shouldObservePresenceBOOLYesWhether presence observation should be enabled for groups or not.
stateNSDictionaryNoReference on dictionary which stores key-value pairs based on channel group name and value which should be assigned to it.

Basic Usage

Subscribe to a channel group

NSString *channelGroup = @"family";
/**
Subscription process results arrive to listener which should adopt to
PNObjectEventListener protocol and registered using:
*/
[self.client addListener:self];
[self.client subscribeToChannelGroups:@[channelGroup] withPresence:NO];

// Handle new message from one of channels on which client has been subscribed.
- (void)client:(PubNub *)client didReceiveMessage:(PNMessageResult *)message {

// Handle new message stored in message.data.message
if (![message.data.channel isEqualToString:message.data.subscription]) {

// Message has been received on channel group stored in message.data.subscription.
}
show all 77 lines

Response

@interface PNSubscriberData : PNServiceData

// Name of channel for which subscriber received data.
@property (nonatomic, readonly, strong) NSString *channel;
// Name of channel or channel group (in case if not equal to channel).
@property (nonatomic, nullable, readonly, strong) NSString *subscription;
// Time at which event arrived.
@property (nonatomic, readonly, strong) NSNumber *timetoken;
// Stores reference on metadata information which has been passed along with received event.
@property (nonatomic, nullable, readonly, strong) NSDictionary<NSString *, id> *userMetadata;

@end

@interface PNSubscribeStatus : PNErrorStatus

show all 46 lines

Other Examples

Subscribe to the presence channel of a channel group

note
Requires Stream Controller and Presence add-ons

This method requires both the Stream Controller and Presence add-ons are enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

/**
Subscription process results arrive to listener which should adopt to
PNObjectEventListener protocol and registered using:
*/
[self.client addListener:self];
[self.client subscribeToChannelGroups:@[channelGroup] withPresence:YES];

// Handle new message from one of channels on which client has been subscribed.
- (void)client:(PubNub *)client didReceiveMessage:(PNMessageResult *)message {

// Handle new message stored in message.data.message
if (![message.data.channel isEqualToString:message.data.subscription]) {

// Message has been received on channel group stored in message.data.subscription.
}
show all 102 lines

Unsubscribe

When subscribed to a single channel, this function causes the client to issue a leave from the channel and close any open socket to the PubNub Network. For multiplexed channels, the specified channel(s) will be removed and the socket remains open until there are no more channels remaining in the list.

Unsubscribing from all channels

Unsubscribing from all channels, and then subscribing to a new channel Y is not the same as subscribing to channel Y and then unsubscribing from the previously-subscribed channel(s). Unsubscribing from all channels resets the last-received timetoken and thus, there could be some gaps in the subscription that may lead to message loss.

Method(s)

To Unsubscribe from a channel you can use the following method(s) in the Objective-C SDK:

- (void)unsubscribeFromChannels:(NSArray<NSString *> *)channels 
withPresence:(BOOL)shouldObservePresence;
ParameterTypeRequiredDescription
channelsNSArrayYesList of channel names from which client should try to unsubscribe.
shouldObservePresenceBOOLYesWhether client should disable presence observation on specified channels or keep listening for presence event on them.

Basic Usage

Unsubscribe from a channel:

/**
Unsubscription process results arrive to listener which should adopt to
PNObjectEventListener protocol and registered using:
*/
[self.client addListener:self];
[self.client unsubscribeFromChannels: @[@"my_channel1", @"my_channel2"] withPresence:NO];

// Handle subscription status change.
- (void)client:(PubNub *)client didReceiveStatus:(PNStatus *)status {

if (status.operation == PNUnsubscribeOperation && status.category == PNDisconnectedCategory) {

/**
This is the expected category for an unsubscribe. This means there was no error in
unsubscribing from everything.
show all 18 lines

Response

@interface PNSubscriberData : PNServiceData

// Name of channel for which subscriber received data.
@property (nonatomic, readonly, strong) NSString *channel;
// Name of channel or channel group (in case if not equal to channel).
@property (nonatomic, nullable, readonly, strong) NSString *subscription;
// Time at which event arrived.
@property (nonatomic, readonly, strong) NSNumber *timetoken;
// Stores reference on metadata information which has been passed along with received event.
@property (nonatomic, nullable, readonly, strong) NSDictionary<NSString *, id> *userMetadata;

@end

@interface PNSubscribeStatus : PNErrorStatus

show all 28 lines

Unsubscribe All

Unsubscribe from all channels and all channel groups

Method(s)

- (void)unsubscribeFromAll;

Basic Usage

/**
Unsubscription process results arrive to listener which should adopt to
PNObjectEventListener protocol and registered using:
*/
[self.client addListener:self];
[self.client unsubscribeFromAll];

// Handle subscription status change.
- (void)client:(PubNub *)client didReceiveStatus:(PNStatus *)status {

if (status.operation == PNUnsubscribeOperation && status.category == PNDisconnectedCategory) {

/**
This is the expected category for an unsubscribe. This means there was no error in unsubscribing
from everything.
show all 18 lines

Returns

None

Unsubscribe from a Channel Group

This function lets you Unsubscribe from a Channel Group

Method(s)

To run Unsubscribe from a Channel Group you can use the following method(s) in the Objective-C SDK:

- (void)unsubscribeFromChannelGroups:(NSArray<NSString *> *)groups 
withPresence:(BOOL)shouldObservePresence;
ParameterTypeRequiredDescription
groupsNSArrayYesList of channel group names from which client should try to unsubscribe.
shouldObservePresenceBOOLYesWhether client should disable presence observation on specified channel groups or keep listening for presence event on them.

Basic Usage

Unsubscribe from a Channel Group

/**
Unsubscription process results arrive to listener which should adopt to
PNObjectEventListener protocol and registered using:
*/
[self.client addListener:self];
[self.client unsubscribeFromChannelGroups: @[@"developers"] withPresence:YES];

// Handle subscription status change.
- (void)client:(PubNub *)client didReceiveStatus:(PNStatus *)status {

if (status.operation == PNUnsubscribeOperation && status.category == PNDisconnectedCategory) {

/**
This is the expected category for an unsubscribe. This means there was no error in unsubscribing
from everything.
show all 18 lines

Response

@interface PNSubscriberData : PNServiceData

// Name of channel for which subscriber received data.
@property (nonatomic, readonly, strong) NSString *channel;
// Name of channel or channel group (in case if not equal to channel).
@property (nonatomic, nullable, readonly, strong) NSString *subscription;
// Time at which event arrived.
@property (nonatomic, readonly, strong) NSNumber *timetoken;
// Stores reference on metadata information which has been passed along with received event.
@property (nonatomic, nullable, readonly, strong) NSDictionary<NSString *, id> *userMetadata;

@end

@interface PNSubscribeStatus : PNErrorStatus

show all 28 lines

Presence

This function is used to subscribe to the presence channel. Using Objective-C SDK, if a client becomes disconnected from a channel, it can automatically attempt to reconnect to that channel and retrieve any available messages that were missed during that period by setting restore to true. By default a client will attempt to reconnect after exceeding a 320 second connection timeout.

Method(s)

To do Presence you can use the following method(s) in the Objective-C SDK:

- (void)subscribeToPresenceChannels:(NSArray<NSString *> *)channels;
ParameterTypeRequiredDescription
channelsNSArrayYesList of channel names for which client should try to subscribe on presence observing channels.

Basic Usage

Subscribe to the presence channel: For any given channel there is an associated Presence channel. You can subscribe directly to the channel by appending -pnpres to the channel name. For example the channel named my_channel would have the presence channel named my_channel-pnpres

/**
Subscription process results arrive to listener which should adopt to
PNObjectEventListener protocol and registered using:
*/
[self.client addListener:self];
[self.client subscribeToPresenceChannels:@[@"my_channel"]];

// New presence event handling.
- (void)client:(PubNub *)client didReceivePresenceEvent:(PNPresenceEventResult *)event {

if (![event.data.channel isEqualToString:event.data.subscription]) {

// Presence event has been received on channel group stored in event.data.subscription.
}
else {
show all 31 lines

Response

@interface PNSubscriberData : PNServiceData

// Name of channel for which subscriber received data.
@property (nonatomic, readonly, strong) NSString *channel;
// Name of channel or channel group (in case if not equal to channel).
@property (nonatomic, nullable, readonly, strong) NSString *subscription;
// Time at which event arrived.
@property (nonatomic, readonly, strong) NSNumber *timetoken;
// Stores reference on metadata information which has been passed along with received event.
@property (nonatomic, nullable, readonly, strong) NSDictionary<NSString *, id> *userMetadata;

@end

@interface PNSubscribeStatus : PNErrorStatus

show all 65 lines

Presence Unsubscribe

This function lets you stop monitoring the presence of the channel(s). The channel(s) will be removed and the socket remains open until there are no more channels remaining in the list.

Method(s)

To Unsubscribe from Presence of a channel you can use the following method(s) in the Objective-C SDK:

- (void)unsubscribeFromPresenceChannels:(NSArray<NSString *> *)channels;
ParameterTypeRequiredDescription
channelsNSArrayYesList of channel names for which client should try to unsubscribe from presence observing channels

Basic Usage

Unsubscribe from the presence channel:

[self.client unsubscribeFromChannelGroups:@[@"developers"] withPresence:YES];

Response

@interface PNSubscriberData : PNServiceData

// Name of channel for which subscriber received data.
@property (nonatomic, readonly, strong) NSString *channel;
// Name of channel or channel group (in case if not equal to channel).
@property (nonatomic, nullable, readonly, strong) NSString *subscription;
// Time at which event arrived.
@property (nonatomic, readonly, strong) NSNumber *timetoken;
// Stores reference on metadata information which has been passed along with received event.
@property (nonatomic, nullable, readonly, strong) NSDictionary<NSString *, id> *userMetadata;

@end

@interface PNSubscribeStatus : PNErrorStatus

show all 28 lines
Last updated on