Configuration API for PubNub Unity SDK

Unity V4 complete API reference for building Realtime Applications on PubNub, including basic usage and sample code.

Unity Developer Path

Looking for Unity use-cases, white papers, and sample apps? Check out our Unity Developer Path.

Configuration

Description

PNConfiguration instance is storage for user-provided information which describe further PubNub client behavior. Configuration instance contain additional set of properties which allow to perform precise PubNub client configuration.

Method(s)

To create configuration instance you can use the following function in the Unity V4 SDK:

new PNConfiguration();
PropertiesTypeRequiredDefaultDescription
SubscribeKeystringYesSubscribeKey from Admin Portal.
PublishKeystringOptionalPublishKey from Admin Portal (only required if publishing).
SecretKeystringOptionalSecretKey (only required for access operations, recommended to be used on secure servers due to security reasons ).
CipherKeystringOptionalIf cipher is passed, all communications to/from PubNub will be encrypted.
UserIdstringYesUserId to use. You should set a unique identifier for the user or the device that connects to PubNub.

It's a UTF-8 encoded string of up to 64 alphanumeric characters.

If you don't set the UserId, you won't be able to connect to PubNub.
LogVerbosityPNLogVerbosityOptionalPNLogVerbosity.NONESet PNLogVerbosity.BODY to enable debugging. To disable debugging use the option PNLogVerbosity.NONE
AuthKeystringOptionalNot setIf Access Manager is utilized, client will use this authKey in all restricted requests.
SecureboolOptionaltrueUse SSL.
MessageQueueOverflowCountintOptional100When the limit is exceeded by the number of messages received in a single subscribe request, a status event PNRequestMessageCountExceededCategory is fired.
SubscribeTimeoutintOptional310The subscribe request timeout.The value is in seconds.
NonSubscribeTimeoutintOptional10For non subscribe operations (publish, herenow, etc), how long to wait to connect to PubNub before giving up with a connection timeout error.The value is in seconds.
FilterExpressionstringOptionalNot setUsed to subscribe with a custom filter expression.
HeartbeatNotificationOptionPNHeartbeatNotificationOptionsOptionalPNHeartbeatNotificationOptions.FAILURESHeartbeat notifications, by default, the SDK will alert on failed heartbeats (equivalent to: PNHeartbeatNotificationOptions.FAILURES).
Other options such as all heartbeats (PNHeartbeatNotificationOptions.ALL) or no heartbeats (PNHeartbeatNotificationOptions.NONE) are supported.
OriginstringOptionalCustom origin if needed.
ReconnectionPolicyPNReconnectionPolicyOptionalPNReconnectionPolicy.NONESet to PNReconnectionPolicy.LINEAR for automatic reconnects. Use option PNReconnectionPolicy.NONE to disable automatic reconnects. Use option PNReconnectionPolicy.EXPONENTIAL to set exponential retry interval.
PresenceTimeoutintOptional0Use to set custom presence server timeout.The value is in seconds.
PresenceIntervalintOptional0Used to set custom interval to send the ping back to the server. This is automatically set to a recommended value when PresenceTimeout is set to a custom value.The value is in seconds.
MaximumReconnectionRetriesintOptionalinfinitySets how many times to retry to reconnect before giving up.
SuppressLeaveEventsboolOptionalWhen true the SDK doesn't send out the leave requests.
UseRandomInitializationVectorboolOptionaltrueWhen true the initialization vector (IV) is random for all requests (not just for file upload). When false the IV is hard-coded for all requests except for file upload.
UUIDstringYesThis parameter is deprecated, use userId instead.

UUID to use. You should set a unique UUID to identify the user or the device that connects to PubNub.
If you don't set the UUID, you won't be able to connect to PubNub.
Disabling random initialization vector

Disable random initialization vector (IV) only for backward compatibility (<5.0.0) with existing applications. Never disable random IV on new applications.

Basic Usage

Required UserId

Always set the UserId to uniquely identify the user or device that connects to PubNub. This UserId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UserId, you won't be able to connect to PubNub.

PNConfiguration pnConfiguration = new PNConfiguration();
// get subscribeKey from Admin Portal
pnConfiguration.SubscribeKey = "SubscribeKey";// required
// publishKey from Admin Portal (only required if publishing)
pnConfiguration.PublishKey = "PublishKey";
// secretKey (only required for access and history delete operations , keep away from Android/iOS)
pnConfiguration.SecretKey = "SecretKey";
// if cipherKey is passed, all communicatons to/from pubnub will be encrypted
pnConfiguration.CipherKey = "CipherKey";
// User ID to be used as a device identifier
pnConfiguration.UserId = "PubNubUnityExample";
// Enable Debugging
pnConfiguration.LogVerbosity = PNLogVerbosity.BODY;
// if Access Manager is utilized, client will use this authKey in all restricted requests
pnConfiguration.AuthKey = "authKey";
show all 26 lines

Initialization

Include the code

Download the PubNub Unity package and import it to your Unity project by going to Assets -> Import Package -> Custom Package. Now that your PubNub Unity Package has been imported, you must enable it in the Test Runner. To enable the PubNub Unity Package, go to Window -> General -> Test Runner. Click on the mini drop down menu next to the window close button, and click Enable playmode tests for all assemblies. You will have to restart your Unity editor to finalize these changes. Congrats, you are now all setup to start using the PubNub Unity SDK! (OR if using the code from the source add files from PubNubUnity/Assets folder to the Assets folder of your project.)

using PubNubAPI;

Description

This function is used for initializing the PubNub Client API context. This function must be called before attempting to utilize any API functionality in order to establish account level credentials such as PublishKey and SubscribeKey.

Method(s)

To Initialize PubNub you can use the following method(s) in the Unity V4 SDK:

new PubNub(pnConfiguration);
ParameterTypeRequiredDescription
pnConfigurationPNConfigurationYesGoto Configuration for more details.

Basic Usage

Initialize the PubNub client API

Required UserId

Always set the UserId to uniquely identify the user or device that connects to PubNub. This UserId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UserId, you won't be able to connect to PubNub.

PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.SubscribeKey = "my_subkey";
pnConfiguration.PublishKey = "my_pubkey";
pnConfiguration.Secure = true;
pnConfiguration.UserId = "myUniqueUserId";
pubnub = new PubNub(pnConfiguration);

Returns

It returns the PubNub instance for invoking PubNub APIs like Publish(), Subscribe(), History(), HereNow(), etc.

Other Examples

Initialize a non-secure client

Required UserId

Always set the UserId to uniquely identify the user or device that connects to PubNub. This UserId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UserId, you won't be able to connect to PubNub.

PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.SubscribeKey = "my_subkey";
pnConfiguration.PublishKey = "my_pubkey";
pnConfiguration.Secure = true;
pnConfiguration.UserId = "myUniqueUserId";
pubnub = new PubNub(pnConfiguration);

Initialization for a Read-Only client

In the case where a client will only read messages and never publish to a channel, you can simply omit the PublishKey when initializing the client:

Required UserId

Always set the UserId to uniquely identify the user or device that connects to PubNub. This UserId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UserId, you won't be able to connect to PubNub.

PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.SubscribeKey = "my_subkey";

pubnub = new PubNub(pnConfiguration);

Use a custom User ID

Set a custom UserId to identify your users.

Required UserId

Always set the UserId to uniquely identify the user or device that connects to PubNub. This UserId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UserId, you won't be able to connect to PubNub.

PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.SubscribeKey = "mySubscribeKey";
pnConfiguration.PublishKey = "myPublishKey";
pnConfiguration.Secure = true;
pnConfiguration.UserId = "myUniqueUserId";

pubnub = new PubNub(pnConfiguration);

Initializing with SSL Enabled

This examples demonstrates how to enable PubNub Transport Layer Encryption with SSL. Just initialize the client with Secure set to true. The hard work is done, now the PubNub API takes care of the rest. Just subscribe and publish as usual and you are good to go.

Required UserId

Always set the UserId to uniquely identify the user or device that connects to PubNub. This UserId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UserId, you won't be able to connect to PubNub.

PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.SubscribeKey = "my_subkey";
pnConfiguration.PublishKey = "my_pubkey";
pnConfiguration.Secure = true;
pnConfiguration.UserId = "myUniqueUserId";
pubnub = new PubNub(pnConfiguration);
Requires Access Manager add-on

This method requires that the Access Manager add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

Secure your SecretKey

Anyone with the SecretKey can grant and revoke permissions to your app. Never let your SecretKey be discovered, and to only exchange it / deliver it securely. Only use the SecretKey on secure server-side platforms.

When you init with SecretKey, you get root permissions for the Access Manager. With this feature you don't have to grant access to your servers to access channel data. The servers get all access on all channels.

For applications that will administer Access Manager permissions, the API is initialized with the SecretKey as in the following example:

Required UserId

Always set the UserId to uniquely identify the user or device that connects to PubNub. This UserId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UserId, you won't be able to connect to PubNub.

PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.SubscribeKey = "my_subkey";
pnConfiguration.PublishKey = "my_pubkey";
pnConfiguration.SecretKey = "my_secretkey";
pnConfiguration.UserId = "myUniqueUserId";
pnConfiguration.Secure = true;

pubnub = new PubNub(pnConfiguration);

Now that the pubnub object is instantiated the client will be able to access the Access Manager functions. The pubnub object will use the SecretKey to sign all Access Manager messages to the PubNub Network.

Event 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

pubnub.SubscribeCallback += SubscribeCallbackHandler;

//Handler
void SubscribeCallbackHandler(object sender, EventArgs e) {
SubscribeEventEventArgs subscribeEventEventArgs = e as SubscribeEventEventArgs;

if (subscribeEventEventArgs.Status != null) {
switch (subscribeEventEventArgs.Status.Category) {
case PNStatusCategory.PNUnexpectedDisconnectCategory:
case PNStatusCategory.PNTimeoutCategory:
pubnub.Publish()
.Channel("my_channel")
.Message("Hello from the PubNub Unity SDK")
.Async((result, status) => {
if(!status.Error){
show all 84 lines

Removing Listeners

pubnub.SubscribeCallback -= SubscribeCallbackHandler;

Handling Disconnects

void SubscribeCallbackHandler(object sender, EventArgs e) {
SubscribeEventEventArgs mea = e as SubscribeEventEventArgs;

if (mea.Status != null) {
switch (mea.Status.Category) {
case PNStatusCategory.PNUnexpectedDisconnectCategory:
case PNStatusCategory.PNTimeoutCategory:
pubnub.Reconnect();
break;
}
}
if (mea.MessageResult != null) {
Debug.Log("SubscribeCallback in message" + mea.MessageResult.Channel + mea.MessageResult.Payload);
}
if (mea.PresenceEventResult != null) {
show all 18 lines

Listener status events

CategoryDescription
PNNetworkIssuesCategoryA subscribe event experienced connection issues when running.
PNReconnectedCategorySDK was able to reconnect to pubnub.
PNConnectedCategorySDK subscribed with a new mix of channels (fired every time the channel / channel group mix changed).
PNAcknowledgmentCategoryUsed API reported success with this status category.
PNAccessDeniedCategoryRequest failed because of access error (active Access Manager). status.AffectedChannels or status.AffectedChannelGroups contain list of channels and/or groups to which user with specified auth key doesn't have access.
PNTimeoutCategoryUsed API didn't receive a response from server in time.
PNDisconnectedCategoryClient unsubscribed from specified real-time data channels.
PNUnexpectedDisconnectCategorySubscribe loop failed and at this moment client is disconnected from real-time data channels. This could due to the machine or device is not connected to Internet or this has been lost, your ISP (Internet Service Provider) is having to troubles or perhaps or the SDK is behind of a proxy.
PNBadRequestCategoryRequest cannot be completed as not all required values have been passed (like subscribe key, publish key) or passed values are of unexpected data type.
PNMalformedFilterExpressionCategorySubscription request cannot be processed as the passed filter expression is malformed and cannot be evaluated.
PNMalformedResponseCategoryRequest received in response non-JSON data. It can be because of an error message from the proxy server (if applicable).
PNDecryptionErrorCategoryHistory API may return this status category in case if some messages can't be decrypted.
PNTLSConnectionFailedCategoryTLS handshake issues. In most cases is because of poor network quality and packets loss and delays.
PNRequestMessageCountExceededCategoryThis status event will be fired each time the client receives more messages than the value of RequestMessageCountThreshold, set in PNConfiguration.
PNReconnectionAttemptsExhaustedIn case of network disconnect the PubNub client SDK will attempt to reconnect a finite number of times after which this status is sent and the re-connection attempts will stop.
PNUnknownCategoryPubNub SDK returns this error for SDK exceptions or when server responds with an error.

UserId

Description

These functions are used to set/get a user ID on the fly.

Method(s)

To set/get UserId you can use the following method(s) in Unity V4 SDK:

UserId
PropertyTypeRequiredDescription
UserIdstringYesUserId to be used as a device identifier. If you don't set the UserId, you won't be able to connect to PubNub.
pnConfiguration.UserId;

A property in the PNConfiguration class.

Basic Usage

Set User ID

Required UserId

Always set the UserId to uniquely identify the user or device that connects to PubNub. This UserId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UserId, you won't be able to connect to PubNub.

PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.UserId = "myUniqueUserId";
pubnub = new PubNub(pnConfiguration);

Get User ID

string UserId = pnConfiguration.UserId;

Authentication Key

Description

Setter and getter for users auth key.

Method(s)

AuthKey
ParameterTypeRequiredDescription
AuthKeystringYesIf Access Manager is utilized, client will use this AuthKey in all restricted requests.
pnConfiguration.AuthKey;

A property in the PNConfiguration class.

Basic Usage

Set Auth Key

PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.AuthKey = "authKey";
pubnub = new PubNub(pnConfiguration);

Get Auth Key

string AuthKey = pnConfiguration.AuthKey;

Returns

Get Auth key returns the current authentication key.

Filter Expression

Requires Stream Controller add-on

This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

Description

Stream filtering allows a subscriber to apply a filter to only receive messages that satisfy the conditions of the filter. The message filter is set by the subscribing client(s) but it is applied on the server side thus preventing unwanted messages (those that do not meet the conditions of the filter) from reaching the subscriber.

To set/get filters you can use the following property. To learn more about filtering, refer to the Publish Messages documentation.

Property(s)

FilterExpression
PropertyTypeRequiredDescription
FilterExpressionstringYesPSV2 feature to Subscribe with a custom filter expression.
pnConfiguration.FilterExpression;

A property in the PNConfiguration class.

Basic Usage

Set Filter Expression

Required UserId

Always set the UserId to uniquely identify the user or device that connects to PubNub. This UserId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UserId, you won't be able to connect to PubNub.

PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.FilterExpression = "such=wow";
pubnub = new PubNub(pnConfiguration);

Get Filter Expression

string FilterExpression = pnConfiguration.FilterExpression;
Last updated on