Publish/Subscribe API for Objective-C SDK
PubNub delivers messages worldwide in less than 30 ms. Send a message to one recipient or broadcast to thousands of subscribers.
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 delivered to all subscribed clients on that channel.
ObjectNode
The new Jackson parser does not recognize JSONObject. Use ObjectNode instead.
- Prerequisites and limitations
- Security
- Message data
- Size and compression
- Publish rate
- Custom message type
- Best practices
- 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.
You can secure the messages with SSL/TLS by setting ssl to true during initialization. You can also encrypt messages.
The message can contain any JSON-serializable data (Objects, Arrays, Ints, Strings) and shouldn't contain any special classes or functions. data should not contain special Objective-C classes or functions as these will not serialize. String content can include any single-byte or multi-byte UTF-8 character.
Don't JSON serialize
You should not JSON serialize the message and meta parameters when sending signals, messages, or files as the serialization is automatic. Pass the full object as the message/meta payload and let PubNub handle everything.
The maximum message size is 32 KiB, including the final escaped character count and the channel name. An optimal message size is under 1800 bytes.
If the message you publish exceeds the configured size, you receive a Message Too Large error. If you want to learn more or calculate your payload size, refer to Message Size Limit.
Message compression can be helpful if you want to send data exceeding the default 32 KiB message size limit, or use bandwidth more efficiently by sending the message payload as the compressed body of an HTTP POST call.
Compression and PubNub SDKs
The C-Core and Objective-C SDKs support compressed messages.
Compressing messages is useful for scenarios that include high channel occupancy and quick exchange of information like ride hailing apps or multiplayer games.
| Compression Trade-off | Details |
|---|---|
| Using Compression | Compression methods and support vary between SDKs. If the receiving SDK doesn't support the sender's compression method, or even if it doesn't support compression at all, the PubNub server automatically changes the compressed message's format so that it is understandable to the recipient. No action is necessary from you. Messages are not compressed by default; you must always explicitly specify that you want to use message compression. |
| Small messages can expand | Compressed messages generally have a smaller size, and can be delivered faster, but only if the original message is over 1 KiB. If you compress a signal (whose size is limited to 64 bytes), the compressed payload exceeds the signal's initial uncompressed size. |
| CPU overhead can increase | While a smaller payload size is an advantage, working with compressed messages uses more CPU time than working with uncompressed messages. CPU time is required to compress the message on the sending client, and again to decompress the message on the receiving client. Efficient resource management is especially important on mobile devices, where increased usage affects battery life. Carefully consider the balance of lower bandwidth and higher speed versus any increased CPU usage. |
Refer to the code below for an example of sending a compressed message:
1[self.client publish:@{@"message": @"This message will be compressed"}
2 toChannel:@"channel_name" compressed:YES
3 withCompletion:^(PNPublishStatus *status) {
4 if (!status.isError) {
5 // Message successfully published to specified channel.
6 } else {
7 // Handle error.
8 }
9}]
You can publish as fast as bandwidth conditions allow. There is a soft limit based on max throughput since messages will be discarded if the subscriber can't keep pace with the publisher.
For example, if 200 messages are published simultaneously before a subscriber has had a chance to receive any, the subscriber may not receive the first 100 messages because the message queue has a limit of only 100 messages stored in memory.
You can optionally provide the customMessageType parameter to add your business-specific label or category to the message, for example text, action, or poll.
- Publish to any given channel in a serial manner (not concurrently).
- Check that the return code is success (for example,
[1,"Sent","136074940..."]) - Publish the next message only after receiving a success return code.
- If a failure code is returned (
[0,"blah","<timetoken>"]), retry the publish. - Avoid exceeding the in-memory queue's capacity of 100 messages. An overflow situation (aka missed messages) can occur if slow subscribers fail to keep up with the publish pace in a given period of time.
- Throttle publish bursts according to your app's latency needs, for example no more than 5 messages per second.
Method(s)
To Publish a message you can use the following method(s) in the Objective-C SDK:
Publish a message with block
1- (void)publish:(id)message
2 toChannel:(NSString *)channel
3 withCompletion:(nullable PNPublishCompletionBlock)block;
| Parameter | Description |
|---|---|
message *Type: id | Reference on Foundation object ( NSString, NSNumber, NSArray, NSDictionary) which will be published. |
channel *Type: NSString | Reference on ID of the channel to which message should be published. |
blockType: PNPublishCompletionBlock | Publish 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
1- (void)publish:(id)message
2 toChannel:(NSString *)channel
3 compressed:(BOOL)compressed
4 withCompletion:(nullable PNPublishCompletionBlock)block;
| Parameter | Description |
|---|---|
message *Type: id | Reference on Foundation object (NSString, NSNumber, NSArray, NSDictionary) which will be published. |
channel *Type: NSString | Reference on ID of the channel to which message should be published. |
compressed *Type: BOOL | Whether 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. |
blockType: PNPublishCompletionBlock | Publish 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
1- (void)publish:(id)message
2 toChannel:(NSString *)channel
3 storeInHistory:(BOOL)shouldStore
4 withCompletion:(nullable PNPublishCompletionBlock)block;
| Parameter | Description |
|---|---|
message *Type: id | Reference on Foundation object (NSString, NSNumber, NSArray,NSDictionary) which will be published. |
channel *Type: NSString | Reference on ID of the channel to which message should be published. |
shouldStore *Type: BOOL | With NO this message later won't be fetched using Message Persistence API. |
blockType: PNPublishCompletionBlock | Publish 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
1- (void)publish:(id)message
2 toChannel:(NSString *)channel
3 storeInHistory:(BOOL)shouldStore
4 compressed:(BOOL)compressed
5 withCompletion:(nullable PNPublishCompletionBlock)block;
| Parameter | Description |
|---|---|
message *Type: id | Reference on Foundation object (NSString, NSNumber, NSArray,NSDictionary) which will be published. |
channel *Type: NSString | Reference on ID of the channel to which message should be published. |
shouldStore *Type: BOOL | With NO this message later won't be fetched using Message Persistence API. |
compressed *Type: BOOL | Compression useful in case if large data should be published, in another case it will lead to packet size grow. |
blockType: PNPublishCompletionBlock | Publish 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
1- (void)publish:(nullable id)message
2 toChannel:(NSString *)channel
3 mobilePushPayload:(nullable NSDictionary<NSString *, id> *)payloads
4 withCompletion:(nullable PNPublishCompletionBlock)block;
| Parameter | Description |
|---|---|
messageType: id | Reference on Foundation object (NSString, NSNumber, NSArray, NSDictionary) which will be published. |
channel *Type: NSString | Reference on ID of the channel to which message should be published. |
payloadsType: NSDictionary | Dictionary with payloads for different vendors (Apple with apns key and Google with fcm). |
blockType: PNPublishCompletionBlock | Publish 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
1- (void)publish:(nullable id)message
2 toChannel:(NSString *)channel
3 mobilePushPayload:(nullable NSDictionary<NSString *, id> *)payloads
4 compressed:(BOOL)compressed
5 withCompletion:(nullable PNPublishCompletionBlock)block;
| Parameter | Description |
|---|---|
messageType: id | Reference on Foundation object (NSString, NSNumber, NSArray, NSDictionary) which will be published. |
channel *Type: NSString | Reference on ID of the channel to which message should be published. |
payloads *Type: NSDictionary | Dictionary with payloads for different vendors (Apple with apns key and Google with fcm). |
compressed *Type: BOOL | Compression useful in case if large data should be published, in another case it will lead to packet size grow. |
blockType: PNPublishCompletionBlock | Publish 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
1- (void)publish:(nullable id)message
2 toChannel:(NSString *)channel
3 mobilePushPayload:(nullable NSDictionary<NSString *, id> *)payloads
4 storeInHistory:(BOOL)shouldStore
5 withCompletion:(nullable PNPublishCompletionBlock)block;
| Parameter | Description |
|---|---|
messageType: id | Reference on Foundation object (NSString, NSNumber, NSArray,NSDictionary) which will be published. |
channel *Type: NSString | Reference on ID of the channel to which message should be published. |
payloadsType: NSDictionary | Dictionary with payloads for different vendors (Apple with apns key and Google with fcm). |
shouldStore *Type: BOOL | With NO this message later won't be fetched using Message Persistence API. |
blockType: PNPublishCompletionBlock | Publish 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
1- (void)publish:(nullable id)message
2 toChannel:(NSString *)channel
3 mobilePushPayload:(nullable NSDictionary<NSString *, id> *)payloads
4 storeInHistory:(BOOL)shouldStore
5 compressed:(BOOL)compressed
6 withCompletion:(nullable PNPublishCompletionBlock)block;
| Parameter | Description |
|---|---|
messageType: id | Reference on Foundation object (NSString, NSNumber, NSArray,NSDictionary) which will be published. |
channel *Type: NSString | Reference on ID of the channel to which message should be published. |
payloadsType: NSDictionary | Dictionary with payloads for different vendors (Apple with "apns" key and Google with "fcm"). |
shouldStore *Type: BOOL | With NO this message later won't be fetched using Message Persistence API. |
compressed *Type: BOOL | Compression useful in case if large data should be published, in another case it will lead to packet size grow. |
blockType: PNPublishCompletionBlock | Publish 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
1- (void)publish:(id)message
2 toChannel:(NSString *)channel
3 withMetadata:(nullable NSDictionary<NSString *, id> *)metadata
4 completion:(nullable PNPublishCompletionBlock)block;
| Parameter | Description |
|---|---|
message *Type: id | The message may be any valid foundation object (String, NSNumber, Array, Dictionary). |
channel *Type: NSString | Specifies channel ID to publish messages to. |
metadataType: NSDictionary | NSDictionary with values which should be used by PubNub service to filter messages. |
blockType: PNPublishCompletionBlock | The 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
1- (void)publish:(id)message
2 toChannel:(NSString *)channel
3 compressed:(BOOL)compressed
4 withMetadata:(nullable NSDictionary<NSString *, id> *)metadata
5 completion:(nullable PNPublishCompletionBlock)block;
| Parameter | Description |
|---|---|
message *Type: id | The message may be any valid foundation object (String, NSNumber, Array, Dictionary). |
channel *Type: NSString | Specifies channel ID to publish messages to. |
compressed *Type: BOOL | If 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. |
metadataType: NSDictionary | NSDictionary with values which should be used by PubNub service to filter messages. |
blockType: PNPublishCompletionBlock | The 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
1- (void)publish:(id)message
2 toChannel:(NSString *)channel
3 storeInHistory:(BOOL)shouldStore
4 withMetadata:(nullable NSDictionary<NSString *, id> *)metadata
5 completion:(nullable PNPublishCompletionBlock)block;
| Parameter | Description |
|---|---|
message *Type: id | The message may be any valid foundation object (String, NSNumber, Array, Dictionary). |
channel *Type: NSString | Specifies channel ID to publish messages to. |
shouldStore *Type: BOOL | If false the messages will not be stored in Message Persistence, default true. |
metadataType: NSDictionary | NSDictionary with values which should be used by PubNub service to filter messages. |
blockType: PNPublishCompletionBlock | The 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
1- (void)publish:(id)message
2 toChannel:(NSString *)channel
3 storeInHistory:(BOOL)shouldStore
4 compressed:(BOOL)compressed
5 withMetadata:(nullable NSDictionary<NSString *, id> *)metadata
6 completion:(nullable PNPublishCompletionBlock)block;
| Parameter | Description |
|---|---|
message *Type: id | The message may be any valid foundation object (String, NSNumber, Array, Dictionary). |
channel *Type: NSString | Specifies channel ID to publish messages to. |
shouldStore *Type: BOOL | If false the messages will not be stored in Message Persistence, default true. |
compressed *Type: BOOL | If 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. |
metadataType: NSDictionary | NSDictionary with values which should be used by PubNub service to filter messages. |
blockType: PNPublishCompletionBlock | The 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
1- (void)publish:(nullable id)message
2 toChannel:(NSString *)channel
3 mobilePushPayload:(nullable NSDictionary<NSString *, id> *)payloads
4 withMetadata:(nullable NSDictionary<NSString *, id> *)metadata
5 completion:(nullable PNPublishCompletionBlock)block;
| Parameter | Description |
|---|---|
messageType: id | The message may be any valid foundation object (String, NSNumber, Array, Dictionary). |
channel *Type: NSString | Specifies channel ID to publish messages to. |
payloadsType: NSDictionary | Dictionary with payloads for different vendors (Apple with aps key and Google with fcm). Either payloads or message should be provided.. |
metadataType: NSDictionary | NSDictionary with values which should be used by PubNub service to filter messages. |
blockType: PNPublishCompletionBlock | The 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
1- (void)publish:(nullable id)message
2 toChannel:(NSString *)channel
3 mobilePushPayload:(nullable NSDictionary<NSString *, id> *)payloads
4 compressed:(BOOL)compressed
5 withMetadata:(nullable NSDictionary<NSString *, id> *)metadata
6 completion:(nullable PNPublishCompletionBlock)block;
| Parameter | Description |
|---|---|
messageType: id | The message may be any valid foundation object (String, NSNumber, Array, Dictionary). |
channel *Type: NSString | Specifies channel ID to publish messages to. |
payloadsType: NSDictionary | Dictionary with payloads for different vendors (Apple with aps key and Google with fcm). Either payloads or message should be provided. |
compressed *Type: BOOL | If 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. |
metadataType: NSDictionary | NSDictionary with values which should be used by PubNub service to filter messages. |
blockType: PNPublishCompletionBlock | The 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
1- (void)publish:(nullable id)message
2 toChannel:(NSString *)channel
3 mobilePushPayload:(nullable NSDictionary<NSString *, id> *)payloads
4 storeInHistory:(BOOL)shouldStore
5 withMetadata:(nullable NSDictionary<NSString *, id> *)metadata
6 completion:(nullable PNPublishCompletionBlock)block;
| Parameter | Description |
|---|---|
messageType: id | The message may be any valid foundation object (String, NSNumber, Array, Dictionary). |
channel *Type: NSString | Specifies channel ID to publish messages to. |
payloadsType: NSDictionary | Dictionary with payloads for different vendors (Apple with a ps key and Google with fcm). Either payloads or message should be provided. |
shouldStore *Type: BOOL | If false the messages will not be stored in Message Persistence, default true. |
metadataType: NSDictionary | NSDictionary with values which should be used by PubNub service to filter messages. |
blockType: PNPublishCompletionBlock | The 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
1- (void)publish:(nullable id)message
2 toChannel:(NSString *)channel
3 mobilePushPayload:(nullable NSDictionary<NSString *, id> *)payloads
4 storeInHistory:(BOOL)shouldStore
5 compressed:(BOOL)compressed
6 withMetadata:(nullable NSDictionary<NSString *, id> *)metadata
7 completion:(nullable PNPublishCompletionBlock)block;
| Parameter | Description |
|---|---|
messageType: id | The message may be any valid foundation object (String, NSNumber, Array, Dictionary). |
channel *Type: NSString | Specifies channel ID to publish messages to. |
payloadsType: NSDictionary | Dictionary with payloads for different vendors (Apple with aps key and Google with fcm). Either payloads or message should be provided. |
shouldStore *Type: BOOL | If false the messages will not be stored in Message Persistence, default true. |
compressed *Type: BOOL | If 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. |
metadataType: NSDictionary | NSDictionary with values which should be used by PubNub service to filter messages. |
blockType: PNPublishCompletionBlock | The 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). |
Sample code
Publish a message to a channel
1#import <Foundation/Foundation.h>
2#import <PubNub/PubNub.h>
3
4// Basic configuration
5PNConfiguration *config = [PNConfiguration configurationWithPublishKey:@"demo"
6 subscribeKey:@"demo"
7 userID:@"publishUser"];
8
9// Optional: Configure encryption for secure messages
10config.cryptoModule = [PNCryptoModule AESCBCCryptoModuleWithCipherKey:@"enigma"
11 randomInitializationVector:YES];
12
13// Create a PubNub client instance
14PubNub *client = [PubNub clientWithConfiguration:config];
15
show all 147 linesSubscribe 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:
1@interface PNPublishData : PNServiceData
2
3@property (nonatomic, readonly, strong) NSNumber *timetoken;
4@property (nonatomic, readonly, strong) NSString *information;
5
6@end
7
8@interface PNPublishStatus : PNAcknowledgmentStatus
9
10@property (nonatomic, readonly, strong) PNPublishData *data;
11
12@end
Other examples
Publish with metadata
1[self publish: @"Hello from the PubNub Objective-C" toChannel:@"chat_channel"
2 withMetadata: @{@"senderID" : @"bob"} completion:^(PNPublishStatus *status) {
3
4 if (!status.isError) {
5
6 // Message successfully published to specified channel.
7 }
8 else {
9
10 /**
11 Handle message publish error. Check 'category' property to find
12 out possible reason because of which request did fail.
13 Review 'errorData' property (which has PNErrorData data type) of status
14 object to get additional information about issue.
15
show all 19 linesPush 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:
1publish()
2 .message(id)
3 .channel(NSString *)
4 .shouldStore(BOOL)
5 .compress(BOOL)
6 .ttl(NSUInteger)
7 .payloads(NSDictionary *)
8 .metadata(NSDictionary *)
9 .customMessageType(NSString*)
10 .performWithCompletion(PNPublishCompletionBlock);
| Parameter | Description |
|---|---|
messageType: id | The message may be any valid foundation object (NSString, NSNumber, NSArray, NSDictionary). |
channel *Type: NSString* | Specifies channel ID to publish messages to. |
shouldStoreType: BOOL | If NO the messages will not be stored in history. Default YES. |
compressType: BOOL | If 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. |
ttlType: NSUInteger | Specify for how many hours published message should be stored. |
payloadsType: NSDictionary | Dictionary with payloads for different vendors (Apple with aps key and Google with fcm). Either payloads or message should be provided. |
metadataType: NSDictionary | NSDictionary with values which should be used by PubNub service to filter messages. |
customMessageTypeType: NSString* | A 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. |
blockType: PNPublishCompletionBlock | The 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). |
Sample code
Publish message which will be stored in Message Persistence for next 16 hours.
1self.client.publish()
2 .channel(@"my_channel")
3 .message(@"Hello from PubNub iOS!")
4 .shouldStore(YES)
5 .ttl(16)
6 .customMessageType(@"text-message")
7 .performWithCompletion(^(PNPublishStatus *status) {
8
9 if (!status.isError) {
10
11 // Message successfully published to specified channel.
12 }
13 else {
14
15 /**
show all 24 linesFire (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:
1fire()
2 .message(id)
3 .channel(NSString *)
4 .compress(BOOL)
5 .payloads(NSDictionary *)
6 .metadata(NSDictionary *)
7 .performWithCompletion(PNPublishCompletionBlock);
| Parameter | Description |
|---|---|
messageType: id | The message may be any valid foundation object (NSString, NSNumber, NSArray, NSDictionary). |
channel *Type: NSString | Specifies channel ID to publish messages to. |
compressType: BOOL | If 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. |
payloadsType: NSDictionary | Dictionary with payloads for different vendors (Apple with aps key and Google with fcm). Either payloads or message should be provided. |
metadataType: NSDictionary | NSDictionary with values which should be used by PubNub service to filter messages. |
blockType: PNPublishCompletionBlock | The 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). |
Sample code
1self.client.fire()
2 .channel(@"my_channel")
3 .message(@"Hello from PubNub iOS!")
4 .shouldStore(YES)
5 .performWithCompletion(^(PNPublishStatus *status) {
6
7 if (!status.isError) {
8
9 // Message successfully published to specified channel.
10 }
11 else {
12
13 /**
14 Handle message publish error. Check 'category' property to find
15 out possible reason because of which request did fail.
show all 22 linesSignal
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:
1- (void)signal:(id)message
2 channel:(NSString *)channel
3 withCompletion:(nullable PNSignalCompletionBlock)block;
| Parameter | Description |
|---|---|
message *Type: id | Object (NSString, NSNumber, NSArray, NSDictionary) which will be sent with signal. |
channel *Type: NSString | ID of the channel to which signal should be sent. |
blockType: PNSignalCompletionBlock | Signal processing completion block which pass only one argument - request processing status to report about how data pushing was successful or not. |
Sample code
Signal a message to a channel
1[self.client signal:@{ @"Hello": @"world" } channel:@"announcement"
2 withCompletion:^(PNSignalStatus *status) {
3
4 if (!status.isError) {
5 // Signal successfully sent to specified channel.
6 } else {
7 /**
8 * Handle signal sending error. Check 'category' property to find out possible issue
9 * because of which request did fail.
10 *
11 * Request can be resent using: [status retry];
12 */
13 }
14}];
Response
Response objects returned by the client when Signal API is used:
1@interface PNSignalStatusData : PNServiceData
2
3@property (nonatomic, readonly, strong) NSNumber *timetoken;
4@property (nonatomic, readonly, strong) NSString *information;
5
6@end
7
8@interface PNSignalStatus : PNAcknowledgmentStatus
9
10@property (nonatomic, readonly, strong) PNSignalStatusData *data;
11
12@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:
1signal()
2 .message(id)
3 .channel(NSString *)
4 .customMessageType(NSString *)
5 .performWithCompletion(PNSignalCompletionBlock);
| Parameter | Description |
|---|---|
message *Type: Array | Object (NSString, NSNumber, NSArray, NSDictionary) which will be sent with signal. |
channel *Type: String | ID of the channel to which signal should be sent. |
customMessageTypeType: NSString* | A 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. |
blockType: PNSignalCompletionBlock | Signal processing completion block which pass only one argument - request processing status to report about how data pushing was successful or not. |
Sample code
Signal a message to a channel
1self.client.signal().message(@{ @"Hello": @"world" }).channel(@"announcement").customMessageType(@"text-message-signal").performWithCompletion(^(PNSignalStatus *status) {
2
3 if (!status.isError) {
4 // Signal successfully sent to specified channel.
5 } else {
6 /**
7 * Handle signal sending error. Check 'category' property to find out possible issue
8 * because of which request did fail.
9 *
10 * Request can be resent using: [status retry];
11 */
12 }
13});
Response
Response objects which is returned by client when Signal API is used::
1@interface PNSignalStatusData : PNServiceData
2
3@property (nonatomic, readonly, strong) NSNumber *timetoken;
4@property (nonatomic, readonly, strong) NSString *information;
5
6@end
7
8@interface PNSignalStatus : PNAcknowledgmentStatus
9
10@property (nonatomic, readonly, strong) PNSignalStatusData *data;
11
12@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.
No built-in event throttling
The PubNub SDK delivers every incoming event to your listener as it arrives — there is no built-in throttling or rate-limiting on the subscriber side. If you need to control how often your application processes events, wrap your listener callback with a throttle or debounce utility from your language or framework ecosystem.
To reduce the number of messages delivered to your client in the first place, use Subscribe Filters to filter messages server-side before they reach your listener.
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 ID. To subscribe to a channel ID 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:
1- (void)subscribeToChannels:(NSArray<NSString *> *)channels
2 withPresence:(BOOL)shouldObservePresence;
| Parameter | Description |
|---|---|
channels *Type: NSArray | List of channel IDs on which client should try to subscribe. |
shouldObservePresence *Type: BOOL | Whether presence observation should be enabled for channels or not. For information on how to receive presence events and what those events are, refer to Presence Events. |
1- (void)subscribeToChannels:(NSArray<NSString *> *)channels
2 withPresence:(BOOL)shouldObservePresence
3 clientState:(nullable NSDictionary<NSString *, id> *)state;
| Parameter | Description |
|---|---|
channels *Type: NSArray | List of channel IDs on which client should try to subscribe. |
shouldObservePresence *Type: BOOL | Whether presence observation should be enabled for channels or not. |
stateType: NSDictionary | Reference on dictionary which stores key-value pairs based on channel ID and value which should be assigned to it. |
1- (void)subscribeToChannels:(NSArray<NSString *> *)channels
2 withPresence:(BOOL)shouldObservePresence
3 usingTimeToken:(nullable NSNumber *)timeToken;
| Parameter | Description |
|---|---|
channels *Type: NSArray | List of channel IDs on which client should try to subscribe. |
shouldObservePresence *Type: BOOL | Whether presence observation should be enabled for channels or not. |
timeTokenType: NSNumber | Specifies 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. |
1- (void)subscribeToChannels:(NSArray<NSString *> *)channels
2 withPresence:(BOOL)shouldObservePresence
3 usingTimeToken:(nullable NSNumber *)timeToken
4 clientState:(nullable NSDictionary<NSString *, id> *)state;
| Parameter | Description |
|---|---|
channels *Type: NSArray | List of channel IDs on which client should try to subscribe. |
shouldObservePresence *Type: BOOL | Whether presence observation should be enabled for channels or not. |
timeTokenType: NSNumber | Specifies 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. |
stateType: NSDictionary | Reference on dictionary which stores key-value pairs based on channel ID and value which should be assigned to it. |
Sample code
Subscribe to a channel:
1/**
2 Subscription results arrive to a listener which should implement the
3 PNObjectEventListener protocol and be registered as follows:
4 */
5[self.client addListener:self];
6[self.client subscribeToChannels: @[@"my_channel1", @"my_channel2"] withPresence:NO];
7
8// Handle a new message from a subscribed channel
9- (void)client:(PubNub *)client didReceiveMessage:(PNMessageResult *)message {
10 // Reference to the channel group containing the chat the message was sent to
11 NSString *subscription = message.data.subscription;
12 NSLog(@"%@ sent message to '%@' at %@: %@", message.data.publisher, message.data.channel,
13 message.data.timetoken, message.data.message);
14}
15
show all 97 linesResponse
1@interface PNSubscriberData : PNServiceData
2
3// Name of channel on which subscriber received data.
4@property (nonatomic, readonly, strong) NSString *channel;
5
6// Name of channel or channel group (if not equal to channel name).
7@property (nonatomic, nullable, readonly, strong) NSString *subscription;
8
9// Time at which the event arrived.
10@property (nonatomic, readonly, strong) NSNumber *timetoken;
11
12// Stores a reference to the metadata information passed along with the received event.
13@property (nonatomic, nullable, readonly, strong) NSDictionary<NSString *, id> *userMetadata;
14
15@end
show all 120 lines