Objective-CiOSiOSCocoaiOS SDK V4 Misc API Reference for Realtime Apps

This function will return a 17 digit precision Unix epoch.
 
Timetoken
The timetoken is constructed using the following algorithm:
timetoken = (Unix epoch time in seconds) * 10000000
Example of creating a timetoken for a specific time & date
08/19/2013 @ 9:20pm in UTC = 1376961606
timetoken = 1376961606 * 10000000
timetoken = 13769616060000000
To fetch Time you can use the following method(s) in Objective-C SDK
  1. ParameterTypeRequiredDescription
    blockPNClientTimeTokenReceivingCompleteBlockYesTime request process results handling block which pass two arguments: result - in case of successful request processing data field will contain server-provided time token; status - in case if error occurred during request processing
[self.client timeWithCompletion:^(PNTimeResult *result, PNErrorStatus *status) {

	if (!status) {

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

		/**
		 Handle time token 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];
		 */
	}
}];
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
This function provides a mechanism to calculate resulting message before it will be sent to the PubNub network.
To run Get size of message you can use the following method(s) in the Objective-C SDK
  1. 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. 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. 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. 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 storage API methods group.
    blockPNMessageSizeCalculationCompletionBlockYesReferecnce on block which should be sent, when message size calculation will be completed.
  5. 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. 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. 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. 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.
 [self.client sizeOfMessage: @{@"Hello": @"world"} toChannel: @"announcement"
			 withCompletion:^(NSInteger size) {
 
	// Process calculated target message size.
 }];
The message size
  1. [self.client sizeOfMessage: @{@"Hello": @"World"} toChannel: @"announcement"
    			  withMetadata: @{@"senderID": @"bob"} completion:^(NSInteger size) {
    
    	// Process calculated target message size.
    }];
This function allow to encrypt the data.
To encrypt the data you can use the following method(s) in Objective-C SDK.
  1. ParameterTypeRequiredDescription
    dataNSDataYesReference on NSData object which should be encrypted.
    keyNSStringYesReference on key which should be used to encrypt data basing on it.
  2. 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.
NSString *message = @"No one should see me as plain";
NSData *messageData = [message dataUsingEncoding:NSUTF8StringEncoding];
NSString *secretMessage = [PNAES encrypt:messageData withKey:@"my_cipherkey"];
Encrypted Base64-encoded string received from Foundation object. nil will be returned in case of failure.
This function allow to decrypt the data.
To decrypt the data you can use the following method(s) in Objective-C SDK.
  1. ParameterTypeRequiredDescription
    objectNSStringYesReference on previously encrypted Base64-encoded string which should be decrypted.
    keyNSStringYesReference on key which should be used to decrypt data.
  2. 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.
NSString *encryptedMessage = messagePayload[@"secret"];
NSData *messageData = [PNAES decrypt:encryptedMessage withKey:@"my_cipherkey"];
NSString *decryptedMessage = [[NSString alloc] initWithData:messageData encoding:NSUTF8StringEncoding];
Initial NSData which has been encrypted earlier. nil will be returned in case of decryption error.

PNAPNSNotificationConfiguration instance allow to configure how notification should be delivered using APNS over HTTP/2.

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

  2. 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. 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.
    targets NSArray<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.

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]];

Configured and ready to use PNAPNSNotificationConfiguration instance.

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

  1. ParameterTypeDescription
    configurations NSArray<PNAPNSNotificationConfiguration *> *List of APNS over HTTP/2 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 instance allow to configure APNS notification recipient.

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

  2. 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. 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.

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

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

Configured and ready to use PNAPNSNotificationTarget instance.

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

  1. ParameterTypeDescription
    notificationNSMutableDictionaryObject with parameters which specify user-visible key-value pairs.
    dataNSMutableDictionary Custom 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 instance provides access to options specific only to push notifications sent with MPNS.

  1. 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 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.

  1. 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.
    apns PNAPNSNotificationPayloadYesAccess to APNS specific notification builder.
    mpns PNMPNSNotificationPayloadYesAccess to MPNS specific notification builder.
    fcm PNFCMNotificationPayloadYesAccess to FCM specific notification builder.

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"];

Configured and ready to use PNNotificationsPayload instance.

  1. 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"
            }
        }
    }
  2. 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"
                        }
                    ],
                    "version": "v2"
                }
            ]
        },
        "pn_gcm": {
            "notification": {
                "body": "You have been invited to 'quiz' chat",
                "sound": "default",
                "title": "Chat invitation"
            }
        }
    }
  3. 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",
                            "topic": "com.meetings.chat.app"
                        }
                    ],
                    "version": "v2"
                }
            ]
        },
        "pn_gcm": {
            "notification": {
                "body": "You have been invited to 'quiz' chat",
                "title": "Chat invitation"
            }
        }
    }

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.

  1. 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

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     
}];

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