UnityUnity V4 Storage & Playback API Reference for Realtime Apps

 

These docs are for PubNub 4.x for Unity which is our latest and greatest! For the docs of the older versions of the SDK, please check PubNub 3.x for Unity.

If you have questions about the PubNub for Unity SDK, please contact us at support@pubnub.com.

The PubNub Storage and Playback Service provides realtime access to history for all messages published to PubNub. Each published message is timestamped to the nearest 10 nanoseconds, and is stored 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.

Messages can be stored for a configurable duration or forever, as controlled by the retention policy that is configured on your account. The following options are available: 1 day, 7 days, 1 month, and Forever.


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:

https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-.
This function fetches historical messages of a channel.
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 = false)
  • Search for messages from the oldest end of the timeline by setting Reverse to true.
  • 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 Count 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 Unity V4 SDK
  1. ParameterTypeRequiredDefaultsDescription
    ChannelstringYesSpecifies channel to return history messages from.
    CountintOptional100Specifies the number of historical messages to return.
    ReverseboolOptionalfalseSetting to true will traverse the time line in reverse starting with the oldest message first.
    IncludeTimetokenboolOptionalfalseWhether event dates time tokens should be included in response or not.
    IncludeMetaboolOptionalfalseWhether meta (passed when Publishing the message) should be included in response or not.
    StartlongOptionalTime token delimiting the start of time slice (exclusive) to pull messages from.
    EndlongOptionalTime token delimiting the end of time slice (inclusive) to pull messages from.
    QueryParamDictionary<string, string>OptionalQueryParam accepts a Dictionary object, the keys and values are passed as the query string parameters of the URL called by the API.
    AsyncPNCallbackYesPNCallback of type PNHistoryResult.
 
Using the Reverse parameter:
Messages are always returned sorted in ascending time direction from Storage/History regardless of Reverse. The Reverse direction matters when you have more than 100 (or Count, if it's set) messages in the time interval, in which case Reverse determines the end of the time interval from which it should start retrieving the messages.
Retrieve the last 100 messages on a channel:
pubnub.History()
	.Channel("history_channel")
	.Count(100)
	.Async ((result, status) => {                
		if(status.Error){
			Debug.Log (string.Format("History Error: {0} {1} {2}", status.StatusCode, status.ErrorData, status.Category));
		} else {
			foreach (PNHistoryItemResult histItem in result.Messages){
				Debug.Log(string.Format("histItem: {0}, {1}", histItem.Entry.ToString(), histItem.Timetoken.ToString()));
			}
		}
	});
The History() operation returns a PNHistoryResult which contains the following operations:
MethodTypeDescription
MessagesList<PNHistoryItemResult>List of messages of type PNHistoryItemResult. See PNHistoryItemResult for more details.
StartTimetokenlongStart timetoken.
EndTimetokenlongEnd timetoken.
MethodTypeDescription
TimetokenlongTimetoken of the message.
EntryobjectMessage.
MetaobjectThe meta data (if sent, when publishing the message).
  1. pubnub.History()
    	.Channel("my_channel")
    	.Count(3)
    	.Reverse(true)
    	.Async ((result, status) => {                
    		if(status.Error){
    			Debug.Log (string.Format(" History Error: {0} {1} {2}", status.StatusCode, status.ErrorData, status.Category));
    		} else {
    			foreach (PNHistoryItemResult histItem in result.Messages){
    				Debug.Log(string.Format("histItem: {0}, {1}", histItem.Entry.ToString(), histItem.Timetoken.ToString()));
    			}
    		}
    	});
    if(!status.Error){
    	foreach (PNHistoryItemResult histItem in result.Messages){
    		Debug.Log(string.Format("histItem: {0}, {1}", histItem.Entry.ToString(), histItem.Timetoken.ToString()));
    	}
    }
  2. pubnub.History()
    	.Channel("my_channel")
    	.Start(13847168620721752L)
    	.Reverse(true)
    	.Async ((result, status) => {                
    		if(status.Error){
    			Debug.Log (string.Format(" History Error: {0} {1} {2}", status.StatusCode, status.ErrorData, status.Category));
    		} else {
    			foreach (PNHistoryItemResult histItem in result.Messages){
    				Debug.Log(string.Format("histItem: {0}, {1}", histItem.Entry.ToString(), histItem.Timetoken.ToString()));
    			}
    		}
    	});
    if(!status.Error){
    	foreach (PNHistoryItemResult histItem in result.Messages){
    		Debug.Log(string.Format("histItem: {0}, {1}", histItem.Entry.ToString(), histItem.Timetoken.ToString()));
    	}
    }
  3. pubnub.History()
    	.Channel("my_channel")
    	.Start(-1)
    	.End(13847168819178600L)
    	.Count(100)
    	.Reverse(true)
    	.Async ((result, status) => {                
    		if(status.Error){
    			Debug.Log (string.Format(" History Error: {0} {1} {2}", status.StatusCode, status.ErrorData, status.Category));
    		} else {
    			foreach (PNHistoryItemResult histItem in result.Messages){
    				Debug.Log(string.Format("histItem: {0}, {1}", histItem.Entry.ToString(), histItem.Timetoken.ToString()));
    			}
    		}
    	});
    
    if(!status.Error){
    	foreach (PNHistoryItemResult histItem in result.Messages){
    		Debug.Log(string.Format("histItem: {0}, {1}", histItem.Entry.ToString(), histItem.Timetoken.ToString()));
    	}
    }
  4.  
    Usage!
    You can call the method by passing 0 or a valid time token as the argument.
    void GetHistoryRecursive(long start, string channel) {
        pubnub.History()
    		.Channel(channel)
    		.Start(start)
    		.Reverse(true)
    		.IncludeTimetoken(true)
    		.Async((result, status) => {
                if (status.Error) {
                    Debug.Log(string.Format("In Example, History Error: {0} {1} {2}", status.StatusCode, status.ErrorData, status.Category));
                } else {
                    if ((result.Messages!=null) && (result.Messages.Count>0)) {
                        foreach (PNHistoryItemResult histItem in result.Messages) {
                            Debug.Log(string.Format("histItem: {0}, {1}", histItem.Entry.ToString(), histItem.Timetoken.ToString()));
                        }
                        GetHistoryRecursive(result.EndTimetoken, channel);
                    }
                }
            });
    }
  5. pubnub.History()
        .Channel("my_channel")
        .IncludeTimetoken(true)
        .Count(100)
        .Async((result, status) => {
            if(status.Error){
                Debug.Log (string.Format(" History Error: {0} {1} {2}", status.StatusCode, status.ErrorData, status.Category));
            } else {
                foreach (PNHistoryItemResult histItem in result.Messages){
                    Debug.Log(string.Format("histItem: {0}, {1}", histItem.Entry.ToString(), histItem.Timetoken.ToString()));
                }
            }
        });
    

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:

https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-.

This function fetches historical messages from multiple channels. The includeMessageActions or includeActions flag also allows you to fetch message actions along with the messages.

It's 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.
  • Search for messages from the oldest end of the timeline.
  • 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.
  • Retrieve a specific (maximum) number of messages using the Count parameter.

Batch history returns up to 100 messages on a single channel, or 25 per channel on a maximum of 500 channels. Use the start and end timestamps to page through the next batch of messages.

Start and End parameter usage clarity

If you specify only the Start parameter (without End), you will receive messages that are older than the Start timetoken.

If you specify only the End parameter (without Start), you will receive messages from that End timetoken and newer.

Specify values for both Start and End parameters to retrieve messages between those timetokens (inclusive of the End value).

Keep in mind that you will still receive a maximum of 100 messages (or 25, for multiple channels) even if there are more messages that meet the timetoken values. Iterative calls to history adjusting the Start timetoken are necessary to page through the full set of results if more messages meet the timetoken values.

To run Fetch History, you can use the following method(s) in the Unity V4 SDK:
  1. ParameterTypeRequiredDefaultsDescription
    ChannelsList<string>YesSpecifies channel to return history messages from.
    CountintOptional25Specifies the number of historical messages to return.

    Default and maximum is 100 for a single channel, 25 for multiple channels, and 25 if IncludeMessageActions is true.
    ReverseboolOptionalfalseSetting to true will traverse the time line in reverse starting with the oldest message first.
    IncludeMetaboolOptionalfalseWhether meta (passed when Publishing the message) should be included in response or not.
    IncludeMessageActionsboolOptionalThe flag denoting to retrieve history messages with message actions.
    If true, the method is limited to one channel only.
    StartlongOptionalTime token delimiting the start of time slice (exclusive) to pull messages from.
    EndlongOptionalTime token delimiting the end of time slice (inclusive) to pull messages from.
    QueryParamDictionary<string, string>OptionalQueryParam accepts a Dictionary object, the keys and values are passed as the query string parameters of the URL called by the API.
    AsyncPNCallbackYesPNCallback of type PNHistoryResult.
Retrieve the last message on a channel:
pubnub.FetchMessages()
	.Channels(new List<string>{"channel2"})
	.Async ((result, status) => {             
		if(status.Error){
			Debug.Log (string.Format(" FetchMessages Error: {0} {1} {2}", status.StatusCode, status.ErrorData, status.Category));
		} else {
			Debug.Log (string.Format("In FetchMessages, result: "));//,result.EndTimetoken, result.Messages[0].ToString()));
			foreach(KeyValuePair<string, List<PNMessageResult>> kvp in result.Channels){
				Debug.Log("kvp channelname" + kvp.Key);
				foreach(PNMessageResult pnMessageResut in kvp.Value){
					Debug.Log("Channel: " + pnMessageResut.Channel);
					Debug.Log("payload: " + pnMessageResut.Payload.ToString());
					Debug.Log("timetoken: " + pnMessageResut.Timetoken.ToString());					
				}
			}
		}
	});

The response is of the type Dictionary.

KeyValue
Channels

List of PNMessageResult as shown Here.


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:

https://support.pubnub.com/hc/en-us/articles/360051974791-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 Admin Portal.

Requires Initialization with secret key.

To Delete Messages from History you can use the following method(s) in the Unity V4 SDK.
  1. ParameterTypeRequiredDefaultsDescription
    ChannelsstringYesSpecifies channels to delete messages from.
    StartlongOptionalTime token delimiting the start of time slice (inclusive) to delete messages from.
    EndlongOptionalTime token delimiting the end of time slice (exclusive) to delete messages from.
    QueryParamDictionary<string, string>OptionalQueryParam accepts a Dictionary object, the keys and values are passed as the query string parameters of the URL called by the API.
    AsyncPNCallbackYesPNCallback of type PNDeleteMessagesResult.
pubnub.DeleteMessages()
	.Channel("channel1")
	.Start(15078932998876451)
	.End(15078933628583256)
	.Async((result, status) => {             
		if(!status.Error){
			Debug.Log (string.Format("DateTime {0}, In DeleteMessages Example, Timetoken: {1}", DateTime.UtcNow , result.Message));
		} else {
			Debug.Log (status.Error);
			Debug.Log (status.StatusCode);
			Debug.Log (status.ErrorData.Info);		  
		}
	});
The DeleteMessages() does not return actionable data, be sure to check the status object on the outcome of the operation by checking the status.IsError().

  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.
    pubnub.DeleteMessages()
    	.Channel("channel1")
    	.Start(15526611838554310)
    	.End(15526611838554309)
    	.Async((result, status) => {             
    		if(!status.Error){
    			Debug.Log (string.Format("DateTime {0}, In DeleteMessages Example, Timetoken: {1}", DateTime.UtcNow , result.Message));
    		} else {
    			Debug.Log (status.Error);
    			Debug.Log (status.StatusCode);
    			Debug.Log (status.ErrorData.Info);		  
    		}
    	});

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:

https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-.
Returns the number of messages published on one or more channels since a given time. The count returned is the number of messages in history with a timetoken value greater than or equal to than the passed value in the ChannelsTimetokenparameter.
 For keys with unlimited message retention enabled, this method considers only messages published in the last 7 days.
You can use the following method(s) in the Unity V4 SDK:
  1. ParameterTypeRequiredDefaultsDescription
    ChannelsList<string>YesThe channels to fetch the message count
    ChannelsTimetokenList<long>YesList of timetokens, in order of the channels list. Specify a single timetoken to apply it to all channels. Otherwise, the list of timetokens must be the same length as the list of channels, or the function returns a PNStatuswith an error flag.
    QueryParamDictionary<string, string>OptionalQueryParam accepts a Dictionary object, the keys and values are passed as the query string parameters of the URL called by the API.
    AsyncPNCallbackYesPNCallback of type PNMessageCountsResult.
pubnub.MessageCounts().
    Channels(new List<string>{"channel2"}).
    ChannelsTimetoken(new List<long>{155179501329433}).
    Async((result, status) =>{    
        if(status.Error){
            Debug.Log (string.Format("MessageCounts Error: {0} {1} {2}", status.StatusCode, status.ErrorData, status.Category));
        } else {
            Debug.Log(string.Format("MessageCounts," + result.Channels.Count));
            foreach(KeyValuePair<string, int> kvp in result.Channels){
                Display(string.Format("MessageCounts:-> {0}:{1}", kvp.Key, kvp.Value));
            }                        
        }
    });
The operation returns a PNMessageCountsResult which contains the following operations
MethodTypeDescription
ChannelsDictionary<string, int>Dictionary with key as channel name and value as the count of history messages. Channels without messages have a count of 0. Channels with 10,000 messages or more have a count of 10000.
  1. pubnub.MessageCounts().
        Channels(new List<string>{"channel2"}).
        ChannelsTimetoken(new List<long>{1551795013294,155179501329433})
        Async((result, status) =>{    
            if(status.Error){
                Debug.Log (string.Format("MessageCounts Error: {0} {1} {2}", status.StatusCode, status.ErrorData, status.Category));
            } else {
                Debug.Log(string.Format("MessageCounts," + result.Channels.Count));
                foreach(KeyValuePair<string, int> kvp in result.Channels){
                    Display(string.Format("MessageCounts:-> {0}:{1}", kvp.Key, kvp.Value));
                }                        
            }
        });