Cocoa Publish & Subscribe API Reference for Realtime Apps
Publish
Description
The publish
function is used to send a message to all subscribers of a channel. To publish a message you must first specify a valid publishKey
at initialization. A successfully published message is replicated across the PubNub Real-Time Network and sent simultaneously to all subscribed clients on a channel.
Messages in transit can be secured from potential eavesdroppers with SSL/TLS by setting ssl to true during initialization.
Publish Anytime
It's not required to be subscribed to a channel in order to publish to that channel.
Message Data:
The message argument can contain any JSON serializable data, including: Objects, Arrays, Ints and Strings. data
should not contain special Cocoa 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!
It is important to note that you should not JSON serialize when sending signals/messages via PUBNUB. Why? Because the serialization is done for you automatically. Instead just pass the full object as the message payload. PubNub takes care of everything for you.
Message Size:
The maximum number of characters per message is 32 KiB by default. The maximum message size is based on the final escaped character count, including the channel name. An ideal message size is under 1800 bytes which allows a message to be compressed and sent using single IP datagram (1.5 KiB) providing optimal network performance.
If the message you publish exceeds the configured size, you will receive the following message:
Message Too Large Error
["PUBLISHED",[0,"Message Too Large","13524237335750949"]]
For further details please check: https://support.pubnub.com/hc/en-us/articles/360051495932-Calculating-Message-Payload-Size-Before-Publish
Message Publish Rate:
Messages can be published as fast as bandwidth conditions will 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 messages, the subscriber may not receive the first 100 messages because the message queue has a limit of only 100 messages stored in memory.
Publishing to Multiple Channels:
It is not possible to publish a message to multiple channels simultaneously. The message must be published to one channel at a time.
Publishing Messages Reliably:
There are some best practices to ensure messages are delivered when publishing to a channel:
- Publish to any given channel in a serial manner (not concurrently).
- Check that the return code is success (e.g.
[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 in accordance with your app's latency needs e.g. Publish no faster than 5 msgs per second to any one channel.
Publishing Compressed Messages
Message compression lets you send the message payload as the compressed body of an HTTP POST call.
Every PubNub SDK supports sending messages using the publish()
call in one or more of the following ways:
- Uncompressed, using HTTP GET (message sent in the URI)
- Uncompressed, using HTTP POST (message sent in the body)
- Compressed, using HTTP POST (compressed message sent in the body)
This section outlines what compressing a message means, and how to use compressed messages to your advantage.
Note
Currently, the C and Objective-C SDKs support compressed messages.
Message compression can be helpful if you want to send data exceeding the default 32 KiB message size limit, or use bandwidth more efficiently. 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-offs
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 30 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.
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. Refer to the code below for an example of sending a compressed message.
[self.client publish:@{@"message": @"This message will be compressed"}
toChannel:@"channel_name" compressed:YES
withCompletion:^(PNPublishStatus *status) {
if (!status.isError) {
// Message successfully published to specified channel.
} else {
// Handle error.
}
}]
Method(s)
To Publish a message
you can use the following method(s) in the Cocoa SDK:
- (void)publish:(id)message toChannel:(NSString *)channel withCompletion:(nullable PNPublishCompletionBlock)block;
Parameter Type Required Description message
id Yes Reference on Foundation object ( NSString
,NSNumber
,NSArray
,NSDictionary
) which will be published.channel
NSString Yes Reference on name of the channel
to whichmessage
should be published.block
PNPublishCompletionBlock No Publish
processing completionblock
which pass only one argument - request processing status to report about how data pushing was successful or not.- (void)publish:(id)message toChannel:(NSString *)channel compressed:(BOOL)compressed withCompletion:(nullable PNPublishCompletionBlock)block;
Parameter Type Required Description message
id Yes Reference on Foundation object ( NSString
,NSNumber
,NSArray
,NSDictionary
) which will be published.channel
NSString Yes Reference on name of the channel
to whichmessage
should be published.compressed
BOOL Yes Whether message
should becompressed
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.block
PNPublishCompletionBlock No Publish processing completion block
which pass only one argument - request processing status to report about how data pushing was successful or not.- (void)publish:(id)message toChannel:(NSString *)channel storeInHistory:(BOOL)shouldStore withCompletion:(nullable PNPublishCompletionBlock)block
Parameter Type Required Description message
id Yes Reference on Foundation object
(NSString
,NSNumber
,NSArray
,NSDictionary
) which will be published.channel
NSString Yes Reference on name of the channel
to whichmessage
should be published.shouldStore
BOOL Yes With NO
thismessage
later won't be fetched with history API.block
PNPublishCompletionBlock No Publish
processing completionblock
which pass only one argument - request processing status to report about how data pushing was successful or not.- (void)publish:(id)message toChannel:(NSString *)channel storeInHistory:(BOOL)shouldStore compressed:(BOOL)compressed withCompletion:(nullable PNPublishCompletionBlock)block;
Parameter Type Required Description message
id Yes Reference on Foundation object ( NSString
,NSNumber
,NSArray
,NSDictionary
) which will be published.channel
NSString Yes Reference on name of the channel
to whichmessage
should be published.shouldStore
BOOL Yes With NO
thismessage
later won't be fetched with history API.compressed
BOOL Yes Compression useful in case if large data should be published, in another case it will lead to packet size grow. block
PNPublishCompletionBlock No Publish
processing completionblock
which pass only one argument - request processing status to report about how data pushing was successful or not.- (void)publish:(nullable id)message toChannel:(NSString *)channel mobilePushPayload:(nullable NSDictionary<NSString *, id> *)payloads withCompletion:(nullable PNPublishCompletionBlock)block;
Parameter Type Required Description message
id No Reference on Foundation object
(NSString
,NSNumber
,NSArray
,NSDictionary
) which will be published.channel
NSString Yes Reference on name of the channel
to whichmessage
should be published.payloads
NSDictionary No Dictionary with payloads for different vendors (Apple with apns
key and Google withgcm
).block
PNPublishCompletionBlock No Publish processing completion block which pass only one argument - request processing status to report about how data pushing was successful or not. - (void)publish:(nullable id)message toChannel:(NSString *)channel mobilePushPayload:(nullable NSDictionary<NSString *, id> *)payloads compressed:(BOOL)compressed withCompletion:(nullable PNPublishCompletionBlock)block;
Parameter Type Required Description message
id No Reference on Foundation object
(NSString
,NSNumber
,NSArray
,NSDictionary
) which will be published.channel
NSString Yes Reference on name of the channel
to whichmessage
should be published.payloads
NSDictionary Yes Dictionary with payloads for different vendors (Apple with apns
key and Google withgcm
).compressed
BOOL Yes Compression useful in case if large data should be published, in another case it will lead to packet size grow. block
PNPublishCompletionBlock No Publish processing completion block
which pass only one argument - request processing status to report about how data pushing was successful or not.- (void)publish:(nullable id)message toChannel:(NSString *)channel mobilePushPayload:(nullable NSDictionary<NSString *, id> *)payloads storeInHistory:(BOOL)shouldStore withCompletion:(nullable PNPublishCompletionBlock)block;
Parameter Type Required Description message
id No Reference on Foundation object
(NSString
,NSNumber
,NSArray
,NSDictionary
) which will be published.channel
NSString Yes Reference on name of the channel
to whichmessage
should be published.payloads
NSDictionary No Dictionary with payloads for different vendors (Apple with apns
key and Google withgcm
).shouldStore
BOOL Yes With NO
thismessage
later won't be fetched with history API.block
PNPublishCompletionBlock No Publish processing completion block
which pass only one argument - request processing status to report about how data pushing was successful or not.- (void)publish:(nullable id)message toChannel:(NSString *)channel mobilePushPayload:(nullable NSDictionary<NSString *, id> *)payloads storeInHistory:(BOOL)shouldStore compressed:(BOOL)compressed withCompletion:(nullable PNPublishCompletionBlock)block;
Parameter Type Required Description message
id No Reference on Foundation object
(NSString
,NSNumber
,NSArray
,NSDictionary
) which will be published.channel
NSString Yes Reference on name of the channel
to which message should be published.payloads
NSDictionary No Dictionary with payloads for different vendors (Apple with "apns" key and Google with "gcm"). shouldStore
BOOL Yes With NO
thismessage
later won't be fetched with history API.compressed
BOOL Yes Compression useful in case if large data should be published, in another case it will lead to packet size grow. block
PNPublishCompletionBlock No Publish processing completion block which pass only one argument - request processing status to report about how data pushing was successful or not. - (void)publish:(id)message toChannel:(NSString *)channel withMetadata:(nullable NSDictionary<NSString *, id> *)metadata completion:(nullable PNPublishCompletionBlock)block;
Parameter Type Required Description message
id Yes The message
may be any valid foundationobject
(String
,NSNumber
,Array
,Dictionary
).channel
NSString Yes Specifies channel
name to publish messages to.metadata
NSDictionary No NSDictionary
with values which should be used byPubNub
service to filter messages.block
PNPublishCompletionBlock No 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).- (void)publish:(id)message toChannel:(NSString *)channel compressed:(BOOL)compressed withMetadata:(nullable NSDictionary<NSString *, id> *)metadata completion:(nullable PNPublishCompletionBlock)block;
Parameter Type Required Description message
id Yes The message
may be any valid foundationobject
(String
,NSNumber
,Array
,Dictionary
).channel
NSString Yes Specifies channel
name to publish messages to.compressed
BOOL Yes If true
themessage
will becompressed
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.metadata
NSDictionary No NSDictionary
with values which should be used byPubNub
service to filter messages.block
PNPublishCompletionBlock No 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).- (void)publish:(id)message toChannel:(NSString *)channel storeInHistory:(BOOL)shouldStore withMetadata:(nullable NSDictionary<NSString *, id> *)metadata completion:(nullable PNPublishCompletionBlock)block;
Parameter Type Required Description message
id Yes The message
may be any valid foundationobject
(String
,NSNumber
,Array
,Dictionary
).channel
NSString Yes Specifies channel
name to publish messages to.shouldStore
BOOL Yes If false
the messages will not be stored in history, defaulttrue
.metadata
NSDictionary No NSDictionary
with values which should be used byPubNub
service to filter messages.block
PNPublishCompletionBlock No 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).- (void)publish:(id)message toChannel:(NSString *)channel storeInHistory:(BOOL)shouldStore compressed:(BOOL)compressed withMetadata:(nullable NSDictionary<NSString *, id> *)metadata completion:(nullable PNPublishCompletionBlock)block;
Parameter Type Required Description message
id Yes The message
may be any valid foundationobject
(String
,NSNumber
,Array
,Dictionary
).channel
NSString Yes Specifies channel
name to publish messages to.shouldStore
BOOL Yes If false
the messages will not be stored in history, defaulttrue
.compressed
BOOL Yes If true
themessage
will becompressed
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.metadata
NSDictionary No NSDictionary
with values which should be used byPubNub
service to filter messages.block
PNPublishCompletionBlock No 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).- (void)publish:(nullable id)message toChannel:(NSString *)channel mobilePushPayload:(nullable NSDictionary<NSString *, id> *)payloads withMetadata:(nullable NSDictionary<NSString *, id> *)metadata completion:(nullable PNPublishCompletionBlock)block;
Parameter Type Required Description message
id No The message
may be any valid foundationobject
(String
,NSNumber
,Array
,Dictionary
).channel
NSString Yes Specifies channel
name to publish messages to.payloads
NSDictionary No Dictionary with payloads
for different vendors (Apple withaps
key and Google withgcm
). Either payloads ormessage
should be provided..metadata
NSDictionary No NSDictionary
with values which should be used byPubNub
service to filter messages.block
PNPublishCompletionBlock No 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).- (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;
Parameter Type Required Description message
id No The message
may be any valid foundation object (String
,NSNumber
,Array
,Dictionary
).channel
NSString Yes Specifies channel
name topublish
messages to.payloads
NSDictionary No Dictionary with payloads
for different vendors (Apple withaps
key and Google withgcm
). Eitherpayloads
ormessage
should be provided.compressed
BOOL Yes If true
themessage
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.metadata
NSDictionary No NSDictionary
with values which should be used byPubNub
service to filter messages.block
PNPublishCompletionBlock No 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).- (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;
Parameter Type Required Description message
id No The message
may be any valid foundationobject
(String
,NSNumber
,Array
,Dictionary
).channel
NSString Yes Specifies channel
name to publish messages to.payloads
NSDictionary No Dictionary with payloads
for different vendors (Apple witha ps
key and Google withgcm
). Eitherpayloads
ormessage
should be provided.shouldStore
BOOL Yes If false
the messages will not be stored in history, defaulttrue
.metadata
NSDictionary No NSDictionary
with values which should be used byPubNub
service to filter messages.block
PNPublishCompletionBlock No 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).- (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;
Parameter Type Required Description message
id No The message
may be any valid foundation object (String
,NSNumber
,Array
,Dictionary
).channel
NSString Yes Specifies channel
name topublish
messages to.payloads
NSDictionary No Dictionary with payloads
for different vendors (Apple withaps
key and Google withgcm
). Eitherpayloads
ormessage
should be provided.shouldStore
BOOL Yes If false
the messages will not be stored in history, defaulttrue
.compressed
BOOL Yes If true
themessage
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.metadata
NSDictionary No NSDictionary
with values which should be used byPubNub
service to filter messages.block
PNPublishCompletionBlock No 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).
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.
Request can be resent using: [status retry];
*/
}
}];
Note
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
-
[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. Request can be resent using: [status retry] */ } }];
-
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)
Description
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 Cocoa SDK:
publish().message(id).channel(NSString *).shouldStore(BOOL).compress(BOOL).ttl(NSUInteger).payloads(NSDictionary *).metadata(NSDictionary *).performWithCompletion(PNPublishCompletionBlock);
Parameter Type Required Description message
id No The message
may be any valid foundation object (NSString
,NSNumber
,NSArray
,NSDictionary
).channel
NSString Yes Specifies channel
name topublish
messages to.shouldStore
BOOL No If NO
the messages will not be stored in history.
DefaultYES
.compress
BOOL No If YES
themessage
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.ttl
NSUInteger No Specify for how many hours published message
should be stored.payloads
NSDictionary No Dictionary with payloads
for different vendors (Apple withaps
key and Google withgcm
). Eitherpayloads
ormessage
should be provided.metadata
NSDictionary No NSDictionary
with values which should be used byPubNub
service to filter messages.block
PNPublishCompletionBlock No 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).
Basic Usage
Publish message which will be stored in channel's storage for next 16 hours.
self.client.publish().channel(@"my_channel").message(@"Hello from PubNub iOS!").shouldStore(YES).ttl(16).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.
Review 'errorData' property (which has PNErrorData data type) of status
object to get additional information about issue.
Request can be resent using: [status retry];
*/
}
});
Fire (Builder Pattern)
Description
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 Cocoa SDK:
fire().message(id).channel(NSString *).compress(BOOL).ttl(NSUInteger).payloads(NSDictionary *).metadata(NSDictionary *).performWithCompletion(PNPublishCompletionBlock);
Parameter Type Required Description message
id No The message
may be any valid foundation object (NSString
,NSNumber
,NSArray
,NSDictionary
).channel
NSString Yes Specifies channel
name topublish
messages to.compress
BOOL No If YES
themessage
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.ttl
NSUInteger No Specify for how many hours published message
should be stored.payloads
NSDictionary No Dictionary with payloads
for different vendors (Apple withaps
key and Google withgcm
). Eitherpayloads
ormessage
should be provided.metadata
NSDictionary No NSDictionary
with values which should be used byPubNub
service to filter messages.block
PNPublishCompletionBlock No 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).
Basic Usage
self.client.fire().channel(@"my_channel").message(@"Hello from PubNub iOS!").shouldStore(YES).ttl(16).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.
Review 'errorData' property (which has PNErrorData data type) of status
object to get additional information about issue.
Request can be resent using: [status retry];
*/
}
});
Signal
Description
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 30
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 Cocoa SDK:
(void)signal:(id)message channel:(NSString *)channel withCompletion:(nullable PNSignalCompletionBlock)block
Parameter Type Required Description message
id Yes Object ( NSString
,NSNumber
,NSArray
,NSDictionary
) which will be sent with signal.channel
NSString Yes Name of the channel
to whichsignal
should be sent.block
PNSignalCompletionBlock No Signal 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)
Description
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 Cocoa SDK:
signal().message(id).channel(NSString *).performWithCompletion(PNSignalCompletionBlock)
Parameter Type Required Description message
Array Yes Object ( NSString
,NSNumber
,NSArray
,NSDictionary
) which will be sent with signal.channel
String Yes Name of the channel
to whichsignal
should be sent.block
PNSignalCompletionBlock No Signal 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")
.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
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.
Tip
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 Cocoa 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.
Warning
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 Cocoa SDK:
- (void)subscribeToChannels:(NSArray<NSString *> *)channels withPresence:(BOOL)shouldObservePresence;
Parameter Type Required Description channels
NSArray Yes List of channel
names on which client should try tosubscribe
.shouldObservePresence
BOOL Yes Whether presence observation should be enabled for channels
or not.- (void)subscribeToChannels:(NSArray<NSString *> *)channels withPresence:(BOOL)shouldObservePresence clientState:(nullable NSDictionary<NSString *, id> *)state;
Parameter Type Required Description channels
NSArray Yes List of channel
names on which client should try tosubscribe
.shouldObservePresence
BOOL Yes Whether presence observation should be enabled for channels
or not.state
NSDictionary No Reference 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;
Parameter Type Required Description channels
NSArray Yes List of channel
names on which client should try tosubscribe
.shouldObservePresence
BOOL Yes Whether presence observation should be enabled for channels
or not.timeToken
NSNumber No Specifies time from which to start returning any available cached messages. Message
retrieval withtimetoken
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;
Parameter Type Required Description channels
NSArray Yes List of channel
names on which client should try tosubscribe
.shouldObservePresence
BOOL Yes Whether presence observation should be enabled for channels
or not.timeToken
NSNumber No Specifies time from which to start returning any available cached messages. Message
retrieval withtimetoken
is not guaranteed and should only be considered a best-effort service.state
NSDictionary No Reference 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);
}
// Handle a subscription status change
- (void)client:(PubNub *)client didReceiveStatus:(PNStatus *)status {
if (status.operation == PNSubscribeOperation) {
// Check to see if the message is about a successful subscription or restore
if (status.category == PNConnectedCategory || status.category == PNReconnectedCategory) {
// Status object for those categories can be cast to `PNSubscribeStatus` for use below.
PNSubscribeStatus *subscribeStatus = (PNSubscribeStatus *)status;
if (subscribeStatus.category == PNConnectedCategory) {
// For a subscribe, this is expected, and means there are no errors or issues
}
else {
// This usually occurs if there is a transient error. The subscribe fails but
// then reconnects, and there is no longer any issue.
}
}
else if (status.category == PNUnexpectedDisconnectCategory) {
// This is usually an issue with the internet connection.
// This is an error: handle appropriately, and retry will be called automatically.
}
// An issue occurred while the client tried to subscribe,
// or the client was disconnected from the network
else {
PNErrorStatus *errorStatus = (PNErrorStatus *)status;
if (errorStatus.category == PNAccessDeniedCategory) {
// PAM prohibited this client from subscribing to this channel and channel group.
// This is another explicit error.
}
else {
/**
You can directly specify more errors by creating explicit cases
for other categories of `PNStatusCategory` errors, such as:
- `PNDecryptionErrorCategory`
- `PNMalformedFilterExpressionCategory`
- `PNMalformedResponseCategory`
- `PNTimeoutCategory`
- `PNNetworkIssuesCategory`
*/
}
}
}
else if (status.operation == PNUnsubscribeOperation) {
if (status.category == PNDisconnectedCategory) {
// This is the expected category for an unsubscribe.
// There were no errors in unsubscribing from everything.
}
}
else if (status.operation == PNHeartbeatOperation) {
/**
Heartbeat operations can have errors, so check first for an error.
For more information on how to configure heartbeat notifications through the status
PNObjectEventListener callback, refer to
http://www.pubnub.com/docs/sdks/objective-c/api-reference/configuration#configuration_basic_usage
*/
if (!status.isError) { /* Heartbeat operation was successful */ }
else { /* There was an error with the heartbeat operation: handle it here */ }
}
}
// Handle a new signal from a subscribed channel
- (void)client:(PubNub *)client didReceiveSignal:(PNSignalResult *)signal {
NSLog(@"%@ sent signal to '%@' at %@: %@", message.data.publisher, message.data.channel,
message.data.timetoken, message.data.message);
}
// Handle new object event from one of channels on which client has been subscribed.
- (void)client:(PubNub *)client didReceiveObjectEvent:(PNObjectEventResult *)event {
NSLog(@"'%@' has been %@'ed at %@", event.data.type, event.data.event,
event.data.timestamp);
}
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
@interface PNSubscribeStatus : PNErrorStatus
// Timetoken used to establish the current subscription cycle.
@property (nonatomic, readonly, strong) NSNumber *currentTimetoken;
// Stores a reference to the previous key used in the subscription cycle to receive
// currentTimetoken along with other events.
@property (nonatomic, readonly, strong) NSNumber *lastTimeToken;
// List of channels to which the client is currently subscribed.
@property (nonatomic, readonly, copy) NSArray<NSString *> *subscribedChannels;
// List of channel group names to which the client is currently subscribed.
@property (nonatomic, readonly, copy) NSArray<NSString *> *subscribedChannelGroups;
// Structured PNResult data field information.
@property (nonatomic, readonly, strong) PNSubscriberData *data;
@end
// Message arrives to event listeners as model described below
@interface PNMessageData : PNSubscriberData
// Message sender identifier.
@property (nonatomic, readonly, strong) NSString *publisher;
// Message delivered through the data object live feed.
@property (nonatomic, nullable, readonly, strong) id message;
@end
@interface PNMessageResult : PNResult
// Stores a reference to the message object from live feed.
@property (nonatomic, readonly, strong) PNMessageData *data;
@end
// Signal arrives to event listeners as model described below
@interface PNSignalData : PNMessageData
// Signal sender identifier.
@property (nonatomic, readonly, strong) NSString *publisher;
// Signal message delivered through the data object live feed.
@property (nonatomic, nullable, readonly, strong) id message;
@end
@interface PNSignalResult : PNResult
// Stores reference to signal object from live feed.
@property (nonatomic, readonly, strong) PNSignalData *data;
@end
// Object events arrive to event listeners as model described below
@interface PNObjectEventData : PNSubscriberData
// This property will be set only if event 'type' is 'channel' and represent channel metadata.
@property (nonatomic, nullable, readonly, strong) PNChannelMetadata *channelMetadata;
// This property will be set only if event 'type' is 'uuid' and represent uuid metadata.
@property (nonatomic, nullable, readonly, strong) PNUUIDMetadata *uuidMetadata;
// This property will be set only if event `type` is 'membership' and represent uuid membership.
@property (nonatomic, nullable, readonly, strong) PNMembership *membership;
// Time when object event has been triggered.
@property (nonatomic, readonly, strong) NSNumber *timestamp;
// Name of action for which object event has been sent.
@property (nonatomic, readonly, strong) NSString *event;
// Type of object which has been changed and triggered event.
@property (nonatomic, readonly, strong) NSString *type;
@end
@interface PNObjectEventResult : PNResult
// Object event object from live feed.
@property (nonatomic, readonly, strong) PNObjectEventData *data;
@end
// Message action events arrive to event listeners as model described below
@interface PNMessageActionData : PNSubscriberData
// Action for which event has been received.
@property (nonatomic, readonly, strong) PNMessageAction *action;
// Name of action for which message action event has been sent ('added') or ('removed')
@property (nonatomic, readonly, copy) NSString *event;
@end
@interface PNMessageActionResult : PNResult
// Message action object from live feed.
@property (nonatomic, readonly, strong) PNMessageActionData *data;
@end
Other Examples
- Subscribing to a Presence channel: Requires Presence add-onRequires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-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 namedmy_channel
would have the presence channel namedmy_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 { // Presence event has been received on channel stored in event.data.channel. } if (![event.data.presenceEvent isEqualToString:@"state-change"]) { NSLog(@"%@ \"%@'ed\"\nat: %@ on %@ (Occupancy: %@)", event.data.presence.uuid, event.data.presenceEvent, event.data.presence.timetoken, event.data.channel, event.data.presence.occupancy); } else { NSLog(@"%@ changed state at: %@ on %@ to: %@", event.data.presence.uuid, event.data.presence.timetoken, event.data.channel, event.data.presence.state); } }
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 ahere_now_refresh
boolean field set totrue
. This indicates to the user that they should do ahereNow
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 }
- Wildcard subscribe to channels: Requires Stream Controller add-onRequires that the Stream Controller add-on is enabled with Enable Wildcard Subscribe checked for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-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 fora.b
,a.c
,a.x
. The wildcarded*
portion refers to any portion of the channel string name after thedot (.)
.Note
3 levels (2 dots) of wildcarding is supported, e.g.:
a.*
a.b.*
[self.client subscribeToChannels: @[@"my_channel.*"] withPresence:YES];
- Subscribing with State: Requires Presence add-onRequires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-Note
Always set the
UUID
to uniquely identify the user or device that connects to PubNub. ThisUUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting theUUID
can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.// 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) { if (!status.isError) { // Client state successfully modified on specified channel. } else { /** Handle client state modification 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. Request can be resent using: [status retry]; */ } }]; } } // 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. } else { // Message has been received on channel stored in message.data.channel. } NSLog(@"Received message: %@ on channel %@ at %@", message.data.message, message.data.channel, message.data.timetoken); }
Subscribe Channel Group
Requires Stream Controller add-on Requires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-
Description
This functions subscribes to a channel group.
Method(s)
To Subscribe to a Channel Group
you can use the following method(s) in the Cocoa SDK:
- (void)subscribeToChannelGroups:(NSArray<NSString *> *)groups withPresence:(BOOL)shouldObservePresence;
Parameter Type Required Description groups
NSArray Yes List of channel
group names on which client should try tosubscribe
.shouldObservePresence
BOOL Yes Whether presence observation should be enabled for groups
or not.- (void)subscribeToChannelGroups:(NSArray<NSString *> *)groups withPresence:(BOOL)shouldObservePresence clientState:(nullable NSDictionary<NSString *, id> *)state;
Parameter Type Required Description groups
NSArray Yes List of channel
group names on which client should try tosubscribe
.shouldObservePresence
BOOL Yes Whether presence observation should be enabled for groups
or not.state
NSDictionary No Reference 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.
}
else {
// Message has been received on channel stored in message.data.channel.
}
NSLog(@"Received message: %@ on channel %@ at %@", message.data.message,
message.data.channel, message.data.timetoken);
}
// Handle subscription status change.
- (void)client:(PubNub *)client didReceiveStatus:(PNStatus *)status {
if (status.operation == PNSubscribeOperation) {
// Check whether received information about successful subscription or restore.
if (status.category == PNConnectedCategory || status.category == PNReconnectedCategory) {
// Status object for those categories can be casted to `PNSubscribeStatus` for use below.
PNSubscribeStatus *subscribeStatus = (PNSubscribeStatus *)status;
if (subscribeStatus.category == PNConnectedCategory) {
// This is expected for a subscribe, this means there is no error or issue whatsoever.
}
else {
/**
This usually occurs if subscribe temporarily fails but reconnects. This means there was
an error but there is no longer any issue.
*/
}
}
else if (status.category == PNUnexpectedDisconnectCategory) {
/**
This is usually an issue with the internet connection, this is an error, handle
appropriately retry will be called automatically.
*/
}
// Looks like some kind of issues happened while client tried to subscribe or disconnected from
// network.
else {
PNErrorStatus *errorStatus = (PNErrorStatus *)status;
if (errorStatus.category == PNAccessDeniedCategory) {
/**
This means that PAM does allow this client to subscribe to this channel and channel group
configuration. This is another explicit error.
*/
}
else {
/**
More errors can be directly specified by creating explicit cases for other error categories
of `PNStatusCategory` such as: `PNDecryptionErrorCategory`,
`PNMalformedFilterExpressionCategory`, `PNMalformedResponseCategory`, `PNTimeoutCategory`
or `PNNetworkIssuesCategory`
*/
}
}
}
}
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
// Timetoken which has been used to establish current subscription cycle.
@property (nonatomic, readonly, strong) NSNumber *currentTimetoken;
// Stores reference on previous key which has been used in subscription cycle to receive
// currentTimetoken along with other events.
@property (nonatomic, readonly, strong) NSNumber *lastTimeToken;
// List of channels on which client currently subscribed.
@property (nonatomic, readonly, copy) NSArray<NSString *> *subscribedChannels;
// List of channel group names on which client currently subscribed.
@property (nonatomic, readonly, copy) NSArray<NSString *> *subscribedChannelGroups;
// Structured PNResult data field information.
@property (nonatomic, readonly, strong) PNSubscriberData *data;
@end
// Message arrive to event listeners as model described below
@interface PNMessageData : PNSubscriberData
// Message sender identifier.
@property (nonatomic, readonly, strong) NSString *publisher;
// Message which has been delivered through data object live feed.
@property (nonatomic, nullable, readonly, strong) id message;
@end
@interface PNMessageResult : PNResult
// Stores reference on message object from live feed.
@property (nonatomic, readonly, strong) PNMessageData *data;
@end
Other Examples
- Subscribe to the presence channel of a channel group: Requires Stream Controller and Presence add-onRequires that both Stream Controller and Presence add-ons are enabled for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-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. } else { // Message has been received on channel stored in message.data.channel. } NSLog(@"Received message: %@ on channel %@ at %@", message.data.message, message.data.channel, message.data.timetoken); } // 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 { // Presence event has been received on channel stored in event.data.channel. } if (![event.data.presenceEvent isEqualToString:@"state-change"]) { NSLog(@"%@ \"%@'ed\"\nat: %@ on %@ (Occupancy: %@)", event.data.presence.uuid, event.data.presenceEvent, event.data.presence.timetoken, event.data.channel, event.data.presence.occupancy); } else { NSLog(@"%@ changed state at: %@ on %@ to: %@", event.data.presence.uuid, event.data.presence.timetoken, event.data.channel, event.data.presence.state); } } // Handle subscription status change. - (void)client:(PubNub *)client didReceiveStatus:(PNStatus *)status { if (status.operation == PNSubscribeOperation) { // Check whether received information about successful subscription or restore. if (status.category == PNConnectedCategory || status.category == PNReconnectedCategory) { // Status object for those categories can be casted to `PNSubscribeStatus` for use below. PNSubscribeStatus *subscribeStatus = (PNSubscribeStatus *)status; if (subscribeStatus.category == PNConnectedCategory) { // This is expected for a subscribe, this means there is no error or issue whatsoever. } else { /** This usually occurs if subscribe temporarily fails but reconnects. This means there was an error but there is no longer any issue. */ } } else if (status.category == PNUnexpectedDisconnectCategory) { /** This is usually an issue with the internet connection, this is an error, handle appropriately retry will be called automatically. */ } // Looks like some kind of issues happened while client tried to subscribe or disconnected from // network. else { PNErrorStatus *errorStatus = (PNErrorStatus *)status; if (errorStatus.category == PNAccessDeniedCategory) { /** This means that PAM does allow this client to subscribe to this channel and channel group configuration. This is another explicit error. */ } else { /** More errors can be directly specified by creating explicit cases for other error categories of `PNStatusCategory` such as: `PNDecryptionErrorCategory`, `PNMalformedFilterExpressionCategory`, `PNMalformedResponseCategory`, `PNTimeoutCategory` or `PNNetworkIssuesCategory` */ } } } }
Unsubscribe
Description
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.
Warning
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 Cocoa SDK:
- (void)unsubscribeFromChannels:(NSArray<NSString *> *)channels withPresence:(BOOL)shouldObservePresence;
Parameter Type Required Description channels
NSArray Yes List of channel
names from which client should try tounsubscribe
.shouldObservePresence
BOOL Yes Whether 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.
*/
}
}
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
// Timetoken which has been used to establish current subscription cycle.
@property (nonatomic, readonly, strong) NSNumber *currentTimetoken;
// Stores reference on previous key which has been used in subscription cycle to receive
// currentTimetoken along with other events.
@property (nonatomic, readonly, strong) NSNumber *lastTimeToken;
// List of channels on which client currently subscribed.
@property (nonatomic, readonly, copy) NSArray<NSString *> *subscribedChannels;
// List of channel group names on which client currently subscribed.
@property (nonatomic, readonly, copy) NSArray<NSString *> *subscribedChannelGroups;
// Structured PNResult data field information.
@property (nonatomic, readonly, strong) PNSubscriberData *data;
@end
Unsubscribe All
Description
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.
*/
}
}
Returns
None
Unsubscribe from a Channel Group
Description
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 Cocoa SDK:
- (void)unsubscribeFromChannelGroups:(NSArray<NSString *> *)groups withPresence:(BOOL)shouldObservePresence;
Parameter Type Required Description groups
NSArray Yes List of channel
group names from which client should try tounsubscribe
.shouldObservePresence
BOOL Yes Whether 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.
*/
}
}
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
// Timetoken which has been used to establish current subscription cycle.
@property (nonatomic, readonly, strong) NSNumber *currentTimetoken;
// Stores reference on previous key which has been used in subscription cycle to receive
// currentTimetoken along with other events.
@property (nonatomic, readonly, strong) NSNumber *lastTimeToken;
// List of channels on which client currently subscribed.
@property (nonatomic, readonly, copy) NSArray<NSString *> *subscribedChannels;
// List of channel group names on which client currently subscribed.
@property (nonatomic, readonly, copy) NSArray<NSString *> *subscribedChannelGroups;
// Structured PNResult data field information.
@property (nonatomic, readonly, strong) PNSubscriberData *data;
@end
Presence
Description
This function is used to subscribe to the presence channel. Using Cocoa 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 Cocoa SDK:
- (void)subscribeToPresenceChannels:(NSArray<NSString *> *)channels;
Parameter Type Required Description channels
NSArray Yes List of channel
names for which client should try tosubscribe
on presence observingchannels
.
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 {
// Presence event has been received on channel stored in event.data.channel.
}
if (![event.data.presenceEvent isEqualToString:@"state-change"]) {
NSLog(@"%@ \"%@'ed\"\nat: %@ on %@ (Occupancy: %@)", event.data.presence.uuid,
event.data.presenceEvent, event.data.presence.timetoken, event.data.channel,
event.data.presence.occupancy);
}
else {
NSLog(@"%@ changed state at: %@ on %@ to: %@", event.data.presence.uuid,
event.data.presence.timetoken, event.data.channel, event.data.presence.state);
}
}
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
// Timetoken which has been used to establish current subscription cycle.
@property (nonatomic, readonly, strong) NSNumber *currentTimetoken;
// Stores reference on previous key which has been used in subscription cycle to receive
// currentTimetoken along with other events.
@property (nonatomic, readonly, strong) NSNumber *lastTimeToken;
// List of channels on which client currently subscribed.
@property (nonatomic, readonly, copy) NSArray<NSString *> *subscribedChannels;
// List of channel group names on which client currently subscribed.
@property (nonatomic, readonly, copy) NSArray<NSString *> *subscribedChannelGroups;
// Structured PNResult data field information.
@property (nonatomic, readonly, strong) PNSubscriberData *data;
@end
// Presence events arrive to event listeners as model described below
@interface PNPresenceDetailsData : PNSubscriberData
// Time when presence event has been triggered.
@property (nonatomic, readonly, strong) NSNumber *timetoken;
// Reference on unique user identifier for which event has been triggered.
@property (nonatomic, nullable, readonly, strong) NSString *uuid;
// List of newly joined subscribers' UUID.
@property (nonatomic, nullable, readonly, strong) NSArray<NSString *> *join;
// List of recently leaved subscribers' UUID.
@property (nonatomic, nullable, readonly, strong) NSArray<NSString *> *leave;
// List of recently UUID of subscribers which leaved by timeout.
@property (nonatomic, nullable, readonly, strong) NSArray<NSString *> *timeout;
// Channel presence information.
@property (nonatomic, readonly, strong) NSNumber *occupancy;
// User changed client state.
@property (nonatomic, nullable, readonly, strong) NSDictionary<NSString *, id> *state;
@end
@interface PNPresenceEventData : PNSubscriberData
// Type of presence event.
@property (nonatomic, readonly, strong) NSString *presenceEvent;
// Additional presence information.
@property (nonatomic, readonly, strong) PNPresenceDetailsData *presence;
@end
@interface PNPresenceEventResult : PNResult
// Stores reference on presence event object from live feed.
@property (nonatomic, readonly, strong) PNPresenceEventData *data;
@end
Presence Unsubscribe
Description
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 Cocoa SDK:
- (void)unsubscribeFromPresenceChannels:(NSArray<NSString *> *)channels;
Parameter Type Required Description channels
NSArray Yes List of channel
names for which client should try tounsubscribe
from presence observingchannels
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
// Timetoken which has been used to establish current subscription cycle.
@property (nonatomic, readonly, strong) NSNumber *currentTimetoken;
// Stores reference on previous key which has been used in subscription cycle to receive
// currentTimetoken along with other events.
@property (nonatomic, readonly, strong) NSNumber *lastTimeToken;
// List of channels on which client currently subscribed.
@property (nonatomic, readonly, copy) NSArray<NSString *> *subscribedChannels;
// List of channel group names on which client currently subscribed.
@property (nonatomic, readonly, copy) NSArray<NSString *> *subscribedChannelGroups;
// Structured PNResult data field information.
@property (nonatomic, readonly, strong) PNSubscriberData *data;
@end
Listeners
Description
You can be notified of connectivity status, message and presence notifications via the listeners.
Listeners should be added before calling the method.
Adding Listeners
Listener's class should conform to PNEventsListener
protocol to have access to available callbacks.
// Adding listener.
[pubnub addListener:self];
// Callbacks listed below.
- (void)client:(PubNub *)pubnub didReceiveMessage:(PNMessageResult *)message {
NSString *channel = message.data.channel; // Channel on which the message has been published
NSString *subscription = message.data.subscription; // Wild-card channel or channel on which PubNub client actually subscribed
NSNumber *timetoken = message.data.timetoken; // Publish timetoken
id msg = message.data.message; // Message payload
NSString *publisher = message.data.publisher; // Message publisher
}
- (void)client:(PubNub *)pubnub didReceiveSignal:(PNSignalResult *)signal {
NSString *channel = message.data.channel; // Channel on which the signal has been published
NSString *subscription = message.data.subscription; // Wild-card channel or channel on which PubNub client actually subscribed
NSNumber *timetoken = message.data.timetoken; // Signal timetoken
id msg = message.data.message; // Signal payload
NSString *publisher = message.data.publisher; // Signal publisher
}
- (void)client:(PubNub *)pubnub didReceiveMessageAction:(PNMessageActionResult *)action {
NSString *channel = action.data.channel; // Channel on which the message has been published
NSString *subscription = action.data.subscription; // Wild-card channel or channel on which PubNub client actually subscribed
NSString *event = action.data.event; // Can be: added or removed
NSString *type = action.data.action.type; // Message action type
NSString *value = action.data.action.value; // Message action value
NSNumber *messageTimetoken = action.data.action.messageTimetoken; // Timetoken of the original message
NSNumber *actionTimetoken = action.data.action.actionTimetoken; // Timetoken of the message action
NSString *uuid = action.data.action.uuid; // UUID of user which added / removed message action
}
- (void)client:(PubNub *)pubnub didReceivePresenceEvent:(PNPresenceEventResult *)event {
NSString *channel = message.data.channel; // Channel on which presence changes
NSString *subscription = message.data.subscription; // Wild-card channel or channel on which PubNub client actually subscribed
NSString *presenceEvent = event.data.presenceEvent; // Can be: join, leave, state-change, timeout or interval
NSNumber *occupancy = event.data.presence.occupancy; // Number of users subscribed to the channel (not available for state-change event)
NSNumber *timetoken = event.data.presence.timetoken; // Presence change timetoken
NSString *uuid = event.data.presence.uuid; // UUID of user for which presence change happened
// Only for 'state-change' event
NSDictionary *state = event.data.presence.state; // User state (only for state-change event)
// Only for 'interval' event
NSArray<NSString *> *join = event.data.presence.join; // UUID of users which recently joined channel
NSArray<NSString *> *leave = event.data.presence.leave; // UUID of users which recently leaved channel
NSArray<NSString *> *timeout = event.data.presence.timeout; // UUID of users which recently timed out on channel
}
- (void)client:(PubNub *)pubnub didReceiveObjectEvent:(PNObjectEventResult *)event {
NSString *channel = event.data.channel; // Channel to which the event belongs
NSString *subscription = event.data.subscription; // Wild-card channel or channel on which PubNub client actually subscribed
NSString *event = event.data.event; // Can be: set or delete
NSString *type = event.data.type; // Entity type: channel, uuid or membership
NSNumber *timestamp = event.data.timestamp; // Event timestamp
PNChannelMetadata *channelMetadata = event.data.channelMetadata; // Updated channel metadata (only for channel entity type)
PNUUIDMetadata *uuidMetadata = event.data.uuidMetadata; // Updated channel metadata (only for uuid entity type)
PNMembership *membership = event.data.membership; // Updated channel metadata (only for membership entity type)
}
- (void)client:(PubNub *)pubnub didReceiveFileEvent:(PNFileEventResult *)event {
NSString *channel = event.data.channel; // Channel to which file has been uploaded
NSString *subscription = event.data.subscription; // Wild-card channel or channel on which PubNub client actually subscribed
id message = event.data.message; // Message added for uploaded file
NSString *publisher = event.data.publisher; // UUID of file uploader
NSURL *fileDownloadURL = event.data.file.downloadURL; // URL which can be used to download file
NSString *fileIdentifier = event.data.file.identifier; // Unique file identifier
NSString *fileName = event.data.file.name; // Name with which file has been stored remotely
}
- (void)client:(PubNub *)pubnub didReceiveStatus:(PNStatus *)status {
PNStatusCategory category = status.category; // One of PNStatusCategory fields to identify status of operation processing
PNOperationType operation = status.operation; // One of PNOperationType fields to identify for which operation status received
BOOL isError = status.isError; // Whether any kind of error happened.
NSInteger statusCode = status.statusCode; // Related request processing status code
BOOL isTLSEnabled = status.isTLSEnabled; // Whether secured connection enabled
NSString *uuid = status.uuid; // UUID which configured for passed client
NSString *authKey = status.authKey; // Auth key configured for passed client
NSString *origin = status.origin; // Origin against which request has been sent
NSURLRequest *clientRequest = status.clientRequest; // Request which has been used to send last request (may be nil)
BOOL willAutomaticallyRetry = status.willAutomaticallyRetry; // Whether client will try to perform automatic retry
// Following information available when operation == PNSubscribeOperation, because status is PNSubscribeStatus instance in this case
PNSubscribeStatus *subscribeStatus = (PNSubscribeStatus *)status;
NSNumber *currentTimetoken = subscribeStatus.currentTimetoken; // Timetoken which has been used for current subscribe request
NSNumber *lastTimeToken = subscribeStatus.lastTimeToken; // Timetoken which has been used for previous subscribe request
NSArray<NSString *> *subscribedChannels = subscribeStatus.subscribedChannels; // List of channels on which client currently subscribed
NSArray<NSString *> *subscribedChannelGroups = subscribeStatus.subscribedChannelGroups; // List of channel groups on which client currently subscribed
NSString *channel = subscribeStatus.data.channel; // Name of channel for which status has been received
NSString *subscription = subscribeStatus.data.subscription; // Wild-card channel or channel on which PubNub client actually subscribed
NSNumber *timetoken = subscribeStatus.data.timetoken; // Timetoken at which event arrived
NSDictionary *userMetadata = subscribeStatus.data.userMetadata; // Metadata / envelope which has been passed along with event
// Following information available when isError == YES, because status is PNErrorStatus instance in this case
PNErrorStatus *errorStatus = (PNErrorStatus *)status;
id associatedObject = errorStatus.associatedObject; // Data which may contain related information (not decrypted message for example)
NSArray<NSString *> *erroredChannels = errorStatus.errorData.channels; // List of channels for which error reported (mostly because of PAM)
NSArray<NSString *> *erroredChannelGroups = errorStatus.errorData.channelGroups; // List of channel groups for which error reported (mostly because of PAM)
NSString *errorInformation = errorStatus.errorData.information; // Stringified information about error
id errorData = errorStatus.errorData.data; // Additional error information from PubNub service
}
Removing Listeners
[pubnub removeListener:self]
Handling Disconnects
SDK performs automated re-connections and call status handler to report back. This will happen forever, but user may decide to stop it.
- (void)client:(PubNub *)pubnub didReceiveStatus:(PNStatus *)status {
if (status.isError && status.willAutomaticallyRetry) {
// Stop automatic retry attempts.
[status cancelAutomaticRetry];
}
}
Listener status events
Category | Description |
---|---|
PNAcknowledgmentCategory | Reported operation request acknowledgment status. |
PNAccessDeniedCategory | PAM permission failure. |
PNTimeoutCategory | Server didn't respond in time for reported operation request. |
PNNetworkIssuesCategory | No connection to Internet. |
PNRequestMessageCountExceededCategory | The SDK announces this error if requestMessageCountThreshold is set, and the number of messages received from PubNub (in-memory cache messages) exceeds the threshold. |
PNConnectedCategory | The SDK subscribed to new channels / channel groups. |
PNReconnectedCategory | The SDK was able to reconnect to PubNub. |
PNDisconnectedCategory | The SDK unsubscribed from channels / channel groups. |
PNUnexpectedDisconnectCategory | The SDK unexpectedly lost ability to receive live updated from PubNub. |
PNRequestURITooLongCategory | Reported operation request URI too long (too many channels / channel groups). |
PNMalformedFilterExpressionCategory | The SDK has been configured with malformed filtering expression. |
PNMalformedResponseCategory | The SDK received unexpected PubNub service response. |
PNDecryptionErrorCategory | The SDK unable to decrypt received message using configured cipherKey . |
PNTLSConnectionFailedCategory | The SDK unable to establish secured connection. |
PNTLSUntrustedCertificateCategory | The SDK unable to check certificates trust chain. |