iOSiOSCocoaObjective-CiOS SDK V4 Storage & Playback API Reference for Realtime Apps

Go to Channel Groups


Requires Storage & Playback add-on XRequires that the Storage & Playback add-on is enabled for your key. See this page on enabling add-on features on your keys:

http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
This function fetches historical messages of a channel.
PubNub Storage/Playback Service provides real-time access to an unlimited history for all messages published to PubNub. Stored messages are replicated across multiple availability zones in several geographical data center locations. Stored messages can be encrypted with AES-256 message encryption ensuring that they are not readable while stored on PubNub's network.
It is possible to control how messages are returned and in what order, for example you can:
  • Search for messages starting on the newest end of the timeline (default behavior - reverse = NO)
  • Search for messages from the oldest end of the timeline by setting reverse to YES.
  • Page through results by providing a start OR end time token.
  • Retrieve a slice of the time line by providing both a start AND end time token.
  • Limit the number of messages to a specific quantity using the limit parameter.
 
Start & End parameter usage clarity:
If only the start parameter is specified (without end), you will receive messages that are older than and up to that start timetoken value.
If only the end parameter is specified (without start) you will receive messages that match that end timetoken value and newer.
Specifying values for both start and end parameters will return messages between those timetoken values (inclusive on the end value).
Keep in mind that you will still receive a maximum of 100 messages even if there are more messages that meet the timetoken values. Iterative calls to history adjusting the start timetoken is necessary to page through the full set of results if more than 100 messages meet the timetoken values.
To run History you can use the following method(s) in the Objective-C SDK
  1. ParameterTypeRequiredDescription
    channelNSStringYesChannel name to retrieve the History information.
    blockPNHistoryCompletionBlockYesHistory pull processing completion block which pass two arguments: result - in case of successful request processing data field will contain results of history request operation; status - in case if error occurred during request processing.
  2. ParameterTypeRequiredDescription
    channelNSStringYesChannel name to retrieve the History information.
    startDateNSNumberNo Reference on time token for oldest event starting from which next should be returned events.
    endDateNSNumberNoReference on time token for latest event till which events should be pulled out.
    blockPNHistoryCompletionBlockYesHistory pull processing completion block which pass two arguments: result - in case of successful request processing data field will contain results of history request operation; status - in case if error occurred during request processing.
  3. ParameterTypeRequiredDescription
    channelNSStringYesChannel name to retrieve the History information.
    startDateNSNumberNo Reference on time token for oldest event starting from which next should be returned events.
    endDateNSNumberNoReference on time token for latest event till which events should be pulled out.
    limitNSUIntegerYesMaximum number of events which should be returned in response (not more then 100).
    blockPNHistoryCompletionBlockYesHistory pull processing completion block which pass two arguments: result - in case of successful request processing data field will contain results of history request operation; status - in case if error occurred during request processing.
  4. ParameterTypeRequiredDescription
    channelNSStringYesChannel name to retrieve the History information.
    startDateNSNumberNo Reference on time token for oldest event starting from which next should be returned events.
    endDateNSNumberNoReference on time token for latest event till which events should be pulled out.
    shouldIncludeTimeTokenBoolYesWhether event dates (time tokens) should be included in response or not.
    blockPNHistoryCompletionBlockYesHistory pull processing completion block which pass two arguments:
    • result - in case of successful request processing data field will contain results of history request operation;
    • status - in case if error occurred during request processing.
  5. ParameterTypeRequiredDescription
    channelNSStringYesChannel name to retrieve the History information.
    startDateNSNumberNo Reference on time token for oldest event starting from which next should be returned events.
    endDateNSNumberNoReference on time token for latest event till which events should be pulled out.
    limitNSUIntegerYesMaximum number of events which should be returned in response (not more then 100).
    shouldIncludeTimeTokenBoolYesWhether event dates (time tokens) should be included in response or not.
    blockPNHistoryCompletionBlockYesHistory pull processing completion block which pass two arguments: result - in case of successful request processing data field will contain results of history request operation; status - in case if error occurred during request processing.
  6. ParameterTypeRequiredDescription
    channelNSStringYesChannel name to retrieve the History information.
    startDateNSNumberNo Reference on time token for oldest event starting from which next should be returned events.
    endDateNSNumberNoReference on time token for latest event till which events should be pulled out.
    limitNSUIntegerYesMaximum number of events which should be returned in response (not more then 100).
    shouldReverseOrderBoolYesWhether events order in response should be reversed or not.
    blockPNHistoryCompletionBlockYesHistory pull processing completion block which pass two arguments:
    • result - in case of successful request processing data field will contain results of history request operation;
    • status - in case if error occurred during request processing.
  7. ParameterTypeRequiredDescription
    channelNSStringYesChannel name to retrieve the History information.
    startDateNSNumberNo Reference on time token for oldest event starting from which next should be returned events.
    endDateNSNumberNoReference on time token for latest event till which events should be pulled out.
    limitNSUIntegerYesMaximum number of events which should be returned in response (not more then 100).
    shouldReverseOrderBoolYesWhether events order in response should be reversed or not.
    shouldIncludeTimeTokenBoolYesWhether event dates (time tokens) should be included in response or not.
    blockPNHistoryCompletionBlockYesHistory pull processing completion block which pass two arguments: result - in case of successful request processing data field will contain results of history request operation; status - in case if error occurred during request processing.
Retrieve the last 100 messages on a channel:
[self.client historyForChannel: @"my_channel" start:nil end:nil limit:100
				withCompletion:^(PNHistoryResult *result, PNErrorStatus *status) {

	if (!status) {

		/**
		 Handle downloaded history using: 
			result.data.start - oldest message time stamp in response
			result.data.end - newest message time stamp in response
			result.data.messages - list of messages
		 */
	}
	else {

		/**
		 Handle message history 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 History API for channel used:

@interface PNHistoryData : PNServiceData

// Channel history messages.
@property (nonatomic, readonly, strong) NSArray *messages;
// History time frame start time.
@property (nonatomic, readonly, strong) NSNumber *start;
// History time frame end time.
@property (nonatomic, readonly, strong) NSNumber *end;

@end


@interface PNHistoryResult : PNResult

// Stores reference on channel history request processing information.
@property (nonatomic, readonly, strong) PNHistoryData *data;

@end
  1. [self.client historyForChannel:@"my_channel" start:nil end:nil limit:3 reverse:YES
    				withCompletion:^(PNHistoryResult *result, PNErrorStatus *status) {
    
    	if (!status) {
    
    		/**
    		 Handle downloaded history using: 
    			result.data.start - oldest message time stamp in response
    			result.data.end - newest message time stamp in response
    			result.data.messages - list of messages
    		 */
    	}
    	else {
    
    		/**
    		 Handle message history 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];
    		 */
    	}
    }];
     [
    	["Pub1","Pub2","Pub3"],
    	13406746729185766,
    	13406746780720711
    ]
    
  2. [self.client historyForChannel:@"my_channel" start:@(13406746780720711) end:nil limit:100
    					   reverse:YES withCompletion:^(PNHistoryResult *result, PNErrorStatus *status) {
    
    	if (!status) {
    
    		/**
    		 Handle downloaded history using: 
    			result.data.start - oldest message time stamp in response
    			result.data.end - newest message time stamp in response
    			result.data.messages - list of messages
    		 */
    	}
    	else {
    
    		/**
    		 Handle message history 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];
    		 */
    	}
    }];
     [
    	["Pub3","Pub4","Pub5"],
    	13406746780720711,
    	13406746845892666
    ]
    
  3. [self.client historyForChannel:@"my_channel" start:nil end:@(13406746780720711) limit:100
    			  includeTimeToken:NO withCompletion:^(PNHistoryResult *result, PNErrorStatus *status) {
    
    	if (!status) {
    
    		/**
    		 Handle downloaded history using: 
    			result.data.start - oldest message time stamp in response
    			result.data.end - newest message time stamp in response
    			result.data.messages - list of messages
    		 */
    	}
    	else {
    
    		/**
    		 Handle message history 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];
    		 */
    	}
    }];
    [
    	["Pub3","Pub4","Pub5"],
    	13406746780720711,
    	13406746845892666
    ]
    
  4.  
    Usage!
    You can call the method by passing 0 or a valid time token as the argument.
    // Pull out all messages newer then message sent at 14395051270438477.
    [self historyFromStartDate:@(14395051270438477) onChannel:@"history_channel" 
    	   withCompletionBlock:^(NSArray *messages) {
    	
    	NSLog(@"Messages from history: %@", messages);
    }];
    
    
    - (void)historyNewerThen:(NSNumber *)beginTime onChannel:(NSString *)channelName 
    	 withCompletionBlock:(void (^)(NSArray *messages))block {
    	
    	NSMutableArray *msgs = [NSMutableArray new];
    	[self historyFromStartDate:beginTime onChannel:channelName
    				  withProgress:^(NSArray *objects) {
    		
    		[msgs addObjectsFromArray:objects];
    		if (objects.count < 100) { block(msgs); }
    	}];
    }
    
    - (void)historyFromStartDate:(NSNumber *)beginTime onChannel:(NSString *)channelName 
    				withProgress:(void (^)(NSArray *objects))block {
    	
    	__weak __typeof(self) weakSelf = self;
    	[self.client historyForChannel:channelName start:beginTime end:nil limit:100 
    						   reverse:NO includeTimeToken:YES 
    				    withCompletion:^(PNHistoryResult *result, PNErrorStatus *status) {
    					  
    		__strong __typeof__(weakSelf) strongSelf = weakSelf;
    		if (!status) {
    
    			block(result.data.messages);
    			if ([result.data.messages count] == 100) {
    
    				[strongSelf historyFromStartDate:result.data.end onChannel:channelName
    									withProgress:block];
    			}
    		}
    		else {
    
    			/**
    			 Handle message history 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];
    			*/
    		}
    	}];
    }
This function fetches historical messages of a channel.
 This method uses the builder pattern, you can remove the args which are optional.
To run History Builder you can use the following method(s) in the Objective-C SDK
  1. ParameterTypeRequiredDescription
    channelsNSArrayYesList of channels for which history should be returned.
    limitNSUIntegerNoMaximum number of messages which should be returned for each channel.

    Maximum: 25.
    completionPNHistoryCompletionBlockYesHistory pull processing completion block which pass two arguments: result - in case of successful request processing data field will contain results of history request operation; status - in case if error occurred during request processing.
self.client.history().channels(@[@"my_channel"]).limit(15).performWithCompletion(^(PNHistoryResult *result, PNErrorStatus *status) {

    if (status == nil) {

        /**
         Handle downloaded history using:
         result.data.channels - dictionary with channels' history. Each key is channel name and value is 
                                list of fetched messages.
         */
    }
    else {

        /**
         Handle message history 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]
         */
    }
});
Requires Storage & Playback add-on XRequires that the Storage & Playback add-on is enabled for your key. See this page on enabling add-on features on your keys:

http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
Removes the messages from the history of a specific channel.
 
There is a setting to accept delete from history requests for a key, which you must enable by checking the Enable Delete-From-History checkbox in the key settings for your key in the Administration Portal.

Requires Initialization with secret key.

To Delete Messages from History you can use the following method(s) in the Objective-C SDK.
  1. - (void)deleteMessagesFromChannel:(NSString *)channel start:(nullable NSNumber *)startDate end:(nullable NSNumber *)endDate withCompletion:(nullable PNMessageDeleteCompletionBlock)block
    ParameterTypeRequiredDescription
    channelNSStringYesName of the channel from which events should be removed.
    startDateNSNumberNoTime token delimiting the start of time slice (inclusive) to delete messages from.
    endDateNSNumberNoTime token delimiting the end of time slice (exclusive) to delete messages from.
    blockPNMessageDeleteCompletionBlockNoEvents remove processing completion block which pass only one argument - request processing status to report about how data pushing was successful or not.
[self.client deleteMessagesFromChannel:@"channel" start:@15101397027611671 end:@15101397427611671 
                        withCompletion:^(PNAcknowledgmentStatus *status) {
                        
    if (!status.isError) {
        // Messages within specified time frame has been removed.
    } else {
       /**
        * Handle message history download error. Check 'category' property to find out possible 
        * issue because of which request did fail.
        *
        * Request can be resent using: [status retry];
        */
    }
}];

  1. To delete a specific message, pass the publish timetoken (received from a successful publish) in the End parameter and timetoken +/- 1 in the Start parameter. e.g. if 15526611838554310 is the publish timetoken, pass 15526611838554309 in Start and 15526611838554310 in End parameters respectively as shown in the following code snippet.
    [self.client deleteMessagesFromChannel:@"channel" start:@15526611838554309 end:@15526611838554310 
                            withCompletion:^(PNAcknowledgmentStatus *status) {
                            
        if (!status.isError) {
            // Messages within specified time frame has been removed.
        } else {
           /**
            * Handle message history download error. Check 'category' property to find out possible 
            * issue because of which request did fail.
            *
            * Request can be resent using: [status retry];
            */
        }
    }];
Requires Storage & Playback add-on XRequires that the Storage & Playback add-on is enabled for your key. See this page on enabling add-on features on your keys:

http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
Removes the messages from the history of a specific channel.
 
There is a setting to accept delete from history requests for a key, which you must enable by checking the Enable Delete-From-History checkbox in the key settings for your key in the Administration Portal.

Requires Initialization with secret key.

To Delete Messages from History you can use the following method(s) in the Objective-C SDK.
  1. - deleteMessage().channel(NSString *).start(NSNumber *).end(NSNumber *).performWithCompletion(PNAcknowledgmentStatus *)
    ParameterTypeRequiredDescription
    channelNSStringYesName of the channel from which events should be removed.
    startDateNSNumberNoTime token delimiting the start of time slice (exclusive) to delete messages from.
    endDateNSNumberNoTime token delimiting the end of time slice (inclusive) to delete messages from.
    blockPNMessageDeleteCompletionBlockNoEvents remove processing completion block which pass only one argument - request processing status to report about how data pushing was successful or not.
self.client.deleteMessage().channel(@"channel").start(@15101397027611671).end(@15101397427611671)
    .performWithCompletion(^(PNAcknowledgmentStatus *status) {
    
    if (!status.isError) {
        // Messages within specified time frame has been removed.
    } else {
       /**
        * Handle message history download error. Check 'category' property to find out possible 
        * issue because of which request did fail.
        *
        * Request can be resent using: [status retry];
        */
    }
});
Requires Storage & Playback add-on XRequires that the Storage & Playback add-on is enabled for your key. See this page on enabling add-on features on your keys:

http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
Specifies the number of historical messages to return per channel. The count returned is the number of messages in history with a timetoken value greater than the passed value in the timetokensparameter.
You can use the following method(s) in the Objective-C SDK:
  1. ParameterTypeRequiredDefaultsDescription
    channelsNSArray<NSString *> *YesThe channels to fetch the message count
    timetokensNSArray<NSNumber *> *YesList with single or multiple timetokens, where each timetoken position in correspond to target channel location in channel names list.
    completion PNMessageCountCompletionBlockYesMessages count fetch completion closure which pass two arguments: result - in case of successful request processing data field will contain results of message count fetch operation; status - in case of error occurred during request processing.
self.client.messageCounts().channels(@[@"unread-channel-1", @"unread-channel-2"])
    .timetokens(@[@(15501015683744028)])
    .performWithCompletion(^(PNMessageCountResult *result, PNErrorStatus *status) {
  
        if (!status.isError) {
            // Client state retrieved number of messages for channels.
        } 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]
            */
        }
    });
@interface PNMessageCountData : PNServiceData

/**
 * @brief Dictionary where each key is name of channel and value is number of messages in it.
 */
@property (nonatomic, readonly, strong) NSDictionary<NSString *, NSNumber *> *channels;

@end
 
@interface PNMessageCountResult : PNResult

/**
 * @brief Message count request processing information.
 */
@property (nonatomic, readonly, strong) PNMessageCountData *data;

@end

  1. self.client.messageCounts().channels(@[@"unread-channel-1", @"unread-channel-2"])
        .timetokens(@[@(15501015683744028), @(15501015683744130)])
        .performWithCompletion(^(PNMessageCountResult *result, PNErrorStatus *status) {
      
            if (!status.isError) {
                // Client state retrieved number of messages for channels.
            } 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]
                */
            }
        });

Go to Mobile Push