Utility Methods API for PubNub Cocoa Objective-C SDK

The methods on this page are utility methods that don't fit into other categories.

Time

Description

This function will return a 17 digit precision Unix epoch.

Algorithm constructing the timetoken
timetoken = (Unix epoch time in seconds) * 10000000

Example of creating a timetoken for a specific time and date:

08/19/2013 @ 9:20pm in UTC = 1376961606
timetoken = 1376961606 * 10000000
timetoken = 13769616060000000

Method(s)

To fetch Time you can use the following method(s) in Cocoa SDK:

­- (void)timeWithCompletion:(PNTimeCompletionBlock)block;
ParameterTypeRequiredDescription
blockPNClientTimeTokenReceivingCompleteBlockYesTime request process results handling block which pass two arguments: result - in case of successful request processing data field will contain server-provided timetoken; status - in case if error occurred during request processing

Basic Usage

Get PubNub Timetoken

[self.client timeWithCompletion:^(PNTimeResult *result, PNErrorStatus *status) {

if (!status) {

// Handle downloaded server timetoken using: result.data.timetoken
}
else {

/**
Handle timetoken download 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];
show all 18 lines

Response

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

@interface PNTimeData : PNServiceData

// Current time on PubNub network servers.
@property (nonatomic, readonly, strong) NSNumber *timetoken;

@end

@interface PNTimeResult : PNResult

// Stores reference on time request processing information.
@property (nonatomic, readonly, strong) PNTimeData *data;

@end

Get size of message

Description

This function provides a mechanism to calculate resulting message before it will be sent to the PubNub network.

Method(s)

To run Get size of message you can use the following method(s) in the Cocoa SDK:

  1. - (void)sizeOfMessage:(id)message toChannel:(NSString *)channel withCompletion:(PNMessageSizeCalculationCompletionBlock)block;
    ParameterTypeRequiredDescription
    messageidYesMessage for which size should be calculated.
    channelNSStringYesName of the channel to which message should be sent (it is part of request URI).
    blockPNMessageSizeCalculationCompletionBlockYesReferecnce on block which should be sent, when message size calculation will be completed.
  2. - (void)sizeOfMessage:(id)message toChannel:(NSString *)channel compressed:(BOOL)compressMessage withCompletion:(PNMessageSizeCalculationCompletionBlock)block;
    ParameterTypeRequiredDescription
    messageidYesMessage for which size should be calculated.
    channelNSStringYesName of the channel to which message should be sent (it is part of request URI).
    compressMessageBoolYesYES in case if message should be compressed before sending to PubNub network.
    blockPNMessageSizeCalculationCompletionBlockYesReferecnce on block which should be sent, when message size calculation will be completed.
  3. - (void)sizeOfMessage:(id)message toChannel:(NSString *)channel storeInHistory:(BOOL)shouldStore withCompletion:(PNMessageSizeCalculationCompletionBlock)block;
    ParameterTypeRequiredDescription
    messageidYesMessage for which size should be calculated.
    channelNSStringYesName of the channel to which message should be sent (it is part of request URI).
    shouldStoreBoolYesYES in case if message should beplaced into history storage.
    blockPNMessageSizeCalculationCompletionBlockYesReferecnce on block which should be sent, when message size calculation will be completed.
  4. - (void)sizeOfMessage:(id)message toChannel:(NSString *)channel compressed:(BOOL)compressMessage storeInHistory:(BOOL)shouldStore withCompletion:(PNMessageSizeCalculationCompletionBlock)block;
    ParameterTypeRequiredDescription
    messageidYesMessage for which size should be calculated.
    channelNSStringYesName of the channel to which message should be sent (it is part of request URI).
    compressMessageBoolYesYES in case if message should be compressed before sending to PubNub network.
    shouldStoreBoolYesNO in case if message shouldn't be available after it has been sent via history Message Persistence API methods group.
    blockPNMessageSizeCalculationCompletionBlockYesReferecnce on block which should be sent, when message size calculation will be completed.
  5. - (void)sizeOfMessage:(id)message toChannel:(NSString *)channel withMetadata:(nullable NSDictionary<NSString *, id> *)metadata completion:(PNMessageSizeCalculationCompletionBlock)block;
    ParameterTypeRequiredDescription
    messageidYesThe message for which the size needs be calculated.
    channelNSStringYesThe channel on which the message has to be sent (it is part of request URI).
    metadataNSDictionaryNoNSDictionary with values which should be used by PubNub service to filter messages.
    blockPNMessageSizeCalculationCompletionBlockYesCompletion block which will be called when the message size calculation is complete.
  6. - (void)sizeOfMessage:(id)message toChannel:(NSString *)channel compressed:(BOOL)compressMessage withMetadata:(nullable NSDictionary<NSString *, id> *)metadata completion:(PNMessageSizeCalculationCompletionBlock)block;
    ParameterTypeRequiredDescription
    messageidYesThe message for which the size needs be calculated.
    channelNSStringYesThe channel on which the message has to be sent (it is part of request URI).
    compressMessageBoolYesShould be true if the message is compressed before sending to PubNub network.
    metadataNSDictionaryNoNSDictionary with values which should be used by PubNub service to filter messages.
    blockPNMessageSizeCalculationCompletionBlockYesCompletion block which will be called when the message size calculation is complete.
  7. - (void)sizeOfMessage:(id)message toChannel:(NSString *)channel storeInHistory:(BOOL)shouldStore withMetadata:(nullable NSDictionary<NSString *, id> *)metadata completion:(PNMessageSizeCalculationCompletionBlock)block;
    ParameterTypeRequiredDescription
    messageidYesThe message for which the size needs be calculated.
    channelNSStringYesThe channel on which the message has to be sent (it is part of request URI).
    shouldStoreBoolYesShould be true if the message is marked to be stored in history.
    metadataNSDictionaryNoNSDictionary with values which should be used by PubNub service to filter messages.
    blockPNMessageSizeCalculationCompletionBlockYesCompletion block which will be called when the message size calculation is complete.
  8. - (void)sizeOfMessage:(id)message toChannel:(NSString *)channel compressed:(BOOL)compressMessage storeInHistory:(BOOL)shouldStore withMetadata:(nullable NSDictionary<NSString *, id> *)metadata completion:(PNMessageSizeCalculationCompletionBlock)block;
    ParameterTypeRequiredDescription
    messageidYesThe message for which the size needs be calculated.
    channelNSStringYesThe channel on which the message has to be sent (it is part of request URI).
    shouldStoreBoolYesShould be true if the message is marked to be stored in history.
    compressMessageBoolYesShould be true if the message is compressed before sending to PubNub network.
    metadataNSDictionaryNoNSDictionary with values which should be used by PubNub service to filter messages.
    blockPNMessageSizeCalculationCompletionBlockYesCompletion block which will be called when the message size calculation is complete.

Basic Usage

Get message size

[self.client sizeOfMessage: @{@"Hello": @"world"} toChannel: @"announcement"
withCompletion:^(NSInteger size) {

// Process calculated target message size.
}];

Returns

The message size

Other Examples

Get Size of Message with metadata

[self.client sizeOfMessage: @{@"Hello": @"World"} toChannel: @"announcement"
withMetadata: @{@"senderID": @"bob"} completion:^(NSInteger size) {

// Process calculated target message size.
}];

Encrypt

Description

This function allows to encrypt the data.

Method(s)

To encrypt the data you can use the following method(s) in Cocoa SDK.

  1. + (nullable NSString *)encrypt:(NSData *)data withKey:(NSString *)key;
    ParameterTypeRequiredDescription
    dataNSDataYesReference on NSData object which should be encrypted.
    keyNSStringYesReference on key which should be used to encrypt data basing on it.
  2. + (nullable NSString *)encrypt:(NSData *)data withKey:(NSString *)key andError:(NSError *__autoreleasing *)error;
    ParameterTypeRequiredDescription
    dataNSDataYesReference on NSData object which should be encrypted.
    keyNSStringYesReference on key which should be used to encrypt data basing on it.
    errorNSErrorNoReference on pointer into which encryption error will be stored in case of encryption failure. Error can be related to JSON string serialization as well as encryption itself.

Basic Usage

Encrypt part of message

NSString *message = @"No one should see me as plain";
NSData *messageData = [message dataUsingEncoding:NSUTF8StringEncoding];
NSString *secretMessage = [PNAES encrypt:messageData withKey:@"my_cipherkey"];

Returns

Encrypted Base64-encoded string received from Foundation object. nil will be returned in case of failure.

Decrypt

Description

This function allows to decrypt the data.

Method(s)

To decrypt the data you can use the following method(s) in Cocoa SDK.

  1. + (nullable NSData *)decrypt:(NSString *)object withKey:(NSString *)key;
    ParameterTypeRequiredDescription
    objectNSStringYesReference on previously encrypted Base64-encoded string which should be decrypted.
    keyNSStringYesReference on key which should be used to decrypt data.
  2. + (nullable NSData *)decrypt:(NSString *)object withKey:(NSString *)key andError:(NSError *__autoreleasing *)error;
    ParameterTypeRequiredDescription
    objectNSStringYesReference on previously encrypted Base64-encoded string which should be decrypted.
    keyNSStringYesReference on key which should be used to decrypt data.
    errorNSErrorNoReference on pointer into which decryption error will be stored in case of decryption failure. Error can be related to JSON string deserialization as well as decryption itself.

Basic Usage

Decrypt part of message

NSString *encryptedMessage = messagePayload[@"secret"];
NSData *messageData = [PNAES decrypt:encryptedMessage withKey:@"my_cipherkey"];
NSString *decryptedMessage = [[NSString alloc] initWithData:messageData encoding:NSUTF8StringEncoding];

Returns

Initial NSData which has been encrypted earlier. nil will be returned in case of decryption error.

Push Notification Configuration

PNAPNSNotificationConfiguration

Description

PNAPNSNotificationConfiguration instance allow to configure how notification should be delivered using HTTP/2-based APNs.

Method(s)

  1. + (instancetype)defaultConfiguration

    Create default configuration with single target configured against PNAPNSDevelopment environment NSBundle.mainBundle.bundleIdentifier as topic name.

  2. + (instancetype)configurationWithTargets:(NSArray<PNAPNSNotificationTarget *> *)targets
    ParameterTypeRequiredDescription
    targetsNSArray< PNAPNSNotificationTarget > YesList of topics which should receive this notification. Default target with NSBundle.mainBundle.bundleIdentifier topic and PNAPNSDevelopment environment will be used if list is empty.
  3. + (instancetype)configurationWithCollapseID:(nullable NSString *)collapseId expirationDate:(nullable NSDate *)date targets:(NSArray<PNAPNSNotificationTarget *> *)targets
    ParameterTypeRequiredDescription
    collapseIdNSStringNoNotification group / collapse identifier. Value will be used in APNs POST request as apns-collapse-id header value.
    dateNSDateNoDate till which APNS will try to deliver notification to target device. Value will be used in APNs POST request as apns-expiration header value.
    targetsNSArray< PNAPNSNotificationTarget > YesList of topics which should receive this notification. Default target with NSBundle.mainBundle.bundleIdentifier topic and PNAPNSDevelopment environment will be used if list is empty.

Basic Usage

Create and configure configuration instance which will collapse invitation notifications and retry to deliver notification (APNS) for next 10 seconds if device off-line:

PNAPNSNotificationConfiguration *configuration = nil;
PNNotificationsPayload *builder = nil;

PNAPNSNotificationTarget *target = [PNAPNSNotificationTarget targetForTopic:@"com.meetings.chat.app"];
NSDate *expirationDate = [NSDate dateWithTimeIntervalSinceNow:10];
configuration = [PNAPNSNotificationConfiguration configurationWithCollapseID:@"invitations"
expirationDate:expirationDate
targets:@[target]];

Response

Configured and ready to use PNAPNSNotificationConfiguration instance.

PNAPNSNotificationPayload

Description

PNAPNSNotificationPayload instance provides access to options specific only to push notifications sent with APNs.

Properties

ParameterTypeDescription
configurationsNSArray< PNAPNSNotificationConfiguration > List of HTTP/2-based APNs delivery configurations. If list is empty when payload for PNAPNS2Push has been requested, it will create default configuration for PNAPNSDevelopment environment and NSBundle.mainBundle.bundleIdentifier as topic name.
notificationNSMutableDictionaryObject with parameters which specify user-visible key-value pairs.
payloadNSMutableDictionaryPlatform specific notification payload. In addition to data required to make notification visual presentation it can be used to pass additional information which should be sent to remote device.
silentBOOLWhether operation system should handle notification layout by default or not. alert, sound and badge will be removed from resulting payload if set to YES.

PNAPNSNotificationTarget

Description

PNAPNSNotificationTarget instance allow to configure APNS notification recipient.

Method(s)

  1. + (instancetype)defaultTarget

    Create default target configured against PNAPNSDevelopment environment NSBundle.mainBundle.bundleIdentifier as topic name.

  2. + (instancetype)targetForTopic:(NSString *)topic
    ParameterTypeRequiredDescription
    topicNSStringYesNotifications topic name (usually it is application's bundle identifier). Value will be used in APNs POST request as apns-topic header value.
  3. + (instancetype)targetForTopic:(NSString *)topic inEnvironment:(PNAPNSEnvironment)environment withExcludedDevices:(nullable NSArray<NSData *> *)excludedDevices
    ParameterTypeRequiredDescription
    topicNSStringYesNotifications topic name (usually it is application's bundle identifier). Value will be used in APNs POST request as apns-topic header value.
    environmentPNAPNSEnvironmentYesOne of PNAPNSEnvironment fields which specify environment within which registered devices to which notifications should be delivered. PNAPNSEnvironment fields:
    • PNAPNSDevelopment
    • PNAPNSProduction
    excludedDevicesNSArray<NSDate > YesList of devices (their push tokens) to which this notification shouldn't be delivered.

Basic Usage

Create and configure APNS notification target, which excludes current device from recipients list:

PNAPNSNotificationTarget *target = [PNAPNSNotificationTarget targetForTopic:@"com.meetings.chat.app"
inEnvironment:PNAPNSProduction
withExcludedDevices:@[self.currentDevicePushToken]];

Response

Configured and ready to use PNAPNSNotificationTarget instance.

PNFCMNotificationPayload

Description

PNFCMNotificationPayload instance provides access to options specific only to push notifications sent with FCM.

Properties

ParameterTypeDescription
notificationNSMutableDictionaryObject with parameters which specify user-visible key-value pairs.
dataNSMutableDictionaryCustom key-value object with additional information which will be passed to device along with displayable notification information. All object and scalar type value should be converted to strings before passing to this object. Keys shouldn't match: from, message_type or start with google or gcm. Also as key can't be used any word defined in this table
silentBOOLWhether operation system should handle notification layout by default or not. notification key with it's content will be moved from root level under data key.
iconNSStringIcon which should be shown on the left from notification title instead of application icon.
tagNSStringUnique notification identifier which can be used to publish update notifications (they will previous notification with same tag).
payloadNSMutableDictionaryPlatform specific notification payload. In addition to data required to make notification visual presentation it can be used to pass additional information which should be sent to remote device.

PNMPNSNotificationPayload

Description

PNMPNSNotificationPayload instance provides access to options specific only to push notifications sent with MPNS.

Properties

ParameterTypeDescription
backContentNSStringMessage which should be shown in notification body (text for back tile). 40 characters long to fit into tile.
backTitleNSStringAdditional information which may explain reason why this notification has been delivered. Maximum 15 characters long.
countNSNumberValue between 1-99 which will be shown on the tile.
titleNSStringTitle of the tile.
typeNSStringType of notification which should be presented to the user.
payloadNSMutableDictionaryPlatform specific notification payload. In addition to data required to make notification visual presentation it can be used to pass additional information which should be sent to remote device.

PNNotificationsPayload

Description

PNNotificationsPayload instance provides convenient method and properties which allow to setup notification for multiple platforms without getting into details how they should be formatted.

Builder instance contain additional set of properties which allow to fine tune payloads for particular platforms and even access to RAW payload dictionaries.

Method(s)

+ (instancetype)payloadsWithNotificationTitle:(nullable NSString *)title body:(nullable NSString *)body
ParameterTypeRequiredDescription
titleNSStringNoShort text which should be shown at the top of notification instead of application name.
bodyNSStringNoMessage which should be shown in notification body (under title line).
subtitleNSStringNoAdditional information which may explain reason why this notification has been delivered.
badgeNSNumberNoNumber which should be shown in space designated by platform (for example atop of application icon).
soundNSStringNoPath to file with sound or name of system sound which should be played upon notification receive.
apnsPNAPNSNotificationPayloadYesAccess to APNS specific notification builder.
fcmPNFCMNotificationPayloadYesAccess to FCM specific notification builder.

Basic Usage

Create notification payload builder with pre-defined notification title and body:

PNNotificationsPayload *builder = nil;
builder = [PNNotificationsPayload payloadsWithNotificationTitle:@"Chat invitation"
body:@"You have been invited to 'quiz' chat"];

Response

Configured and ready to use PNNotificationsPayload instance.

Other Examples

Generate simple notification payload for FCM and APNS

PNNotificationsPayload *builder = nil;
builder = [PNNotificationsPayload payloadsWithNotificationTitle:@"Chat invitation"
body:@"You have been invited to 'quiz' chat"];
builder.sound = @"default";

NSLog(@"Notifications payload: %@", [builder dictionaryRepresentationFor:PNAPNSPush|PNFCMPush]);
Output
{
"pn_apns": {
"aps": {
"alert": {
"body": "You have been invited to 'quiz' chat",
"title": "Chat invitation"
},
"sound": "default"
}
},
"pn_gcm": {
"notification": {
"body": "You have been invited to 'quiz' chat",
"sound": "default",
"title": "Chat invitation"
show all 18 lines

Generate simple notification payload for FCM and HTTP/2-based APNs (default configuration)

PNNotificationsPayload *builder = nil;
builder = [PNNotificationsPayload payloadsWithNotificationTitle:@"Chat invitation"
body:@"You have been invited to 'quiz' chat"];
builder.sound = @"default";

NSLog(@"Notifications payload: %@", [builder dictionaryRepresentationFor:PNAPNS2Push|PNFCMPush]);
Output
{
"pn_apns": {
"aps": {
"alert": {
"body": "You have been invited to 'quiz' chat",
"title": "Chat invitation"
},
"sound": "default"
},
"pn_push": [
{
"targets": [
{
"environment": "development",
"topic": "com.meetings.chat.app"
show all 29 lines

Generate simple notification payload for FCM and HTTP/2-based APNs (custom configuration)

PNAPNSNotificationConfiguration *configuration = nil;
PNNotificationsPayload *builder = nil;

PNAPNSNotificationTarget *target = [PNAPNSNotificationTarget targetForTopic:@"com.meetings.chat.app"];
NSDate *expirationDate = [NSDate dateWithTimeIntervalSinceNow:10];
configuration = [PNAPNSNotificationConfiguration configurationWithCollapseID:@"invitations"
expirationDate:expirationDate
targets:@[target]];

builder = [PNNotificationsPayload payloadsWithNotificationTitle:@"Chat invitation"
body:@"You have been invited to 'quiz' chat"];
builder.apns.configurations = @[configuration];

NSLog(@"Notifications payload: %@", [builder dictionaryRepresentationFor:PNAPNS2Push|PNFCMPush]);
Output
{
"pn_apns": {
"aps": {
"alert": {
"body": "Chat invitation",
"title": "You have been invited to 'quiz' chat"
}
},
"pn_push": [
{
"collapse_id": "invitations",
"expiration": "2019-11-28T22:06:09Z",
"targets": [
{
"environment": "development",
show all 29 lines

Example above show how to create notification payload which APNS will try to redeliver few times (if devices not active) and give up after 10 seconds since moment when it has been scheduled.

Additionally this invitation notification will be grouped along with other invitation notifications (using provided collapse_id as group identifier) and shown as one in notification center.

- (NSDictionary *)dictionaryRepresentationFor:(PNPushType)pushTypes

Build notifications platform for requested platforms (pushTypes).

ParameterTypeRequiredDescription
pushTypesPNPushTypeYesBitfield with fields from PNPushType which specify platforms for which payload should be added to final dictionary. PNPushType fields:
  • PNAPNSPush
  • PNAPNS2Push
  • PNFCMPush
  • PNMPNSPush

Basic Usage

Publish message with notification payload:

PNNotificationsPayload *builder = nil;
builder = [PNNotificationsPayload payloadsWithNotificationTitle:@"Chat invitation"
body:@"You have been invited to 'quiz' chat"];
NSDictionary *payload = [builder dictionaryRepresentationFor:PNAPNS2Push|PNFCMPush];
NSDictionary *message = @{
@"message": @"Max invited you to 'quiz' chat room",
@"roomID": @"ewuiogw9vewg0"
};

[self.client publish:message toChannel:@"chat-bot" mobilePushPayload:payload
withCompletion:^(PNPublishStatus *status) {
// Handle publish results
}];

Response

Dictionary with data, which can be sent with publish method call and trigger remote notifications for specified platforms.