Configuration API for PubNub Unity SDK
Unity complete API reference for building Real-time Applications on PubNub, including basic usage and sample code.
Even though you can configure and initialize the Unity SDK directly from Unity Editor via assets, you can also do it programmatically.
Refer to Getting Started for instructions on how to set up the Unity SDK using assets.
Configuration
A PNConfiguration
instance is the storage for user-provided information that describe further PubNub client behavior.
Method(s)
To create a PNConfiguration
instance, you can use the following function in the Unity SDK:
PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"));
Properties | Type | Required | Description |
---|---|---|---|
SubscribeKey | string | Yes | SubscribeKey from Admin Portal. |
PublishKey | string | Optional | PublishKey from Admin Portal (only required if publishing). |
SecretKey | string | Optional | SecretKey (only required for access operations, keep away from Android). |
UserId | UserId | Yes | UserId to use. The UserId object takes string as an argument. 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 92 alphanumeric characters. If you don't set theUserId , you won't be able to connect to PubNub. |
LogVerbosity | PNLogVerbosity | Yes | Set PNLogVerbosity.BODY to enable debugging. To disable debugging use the option PNLogVerbosity.NONE |
AuthKey | string | Optional | If Access Manager is utilized, client will use this AuthKey in all restricted requests. |
Secure | bool | Optional | Use SSL . |
SubscribeTimeout | int | Optional | How long to keep the subscribe loop running before disconnect. The value is in seconds. |
NonSubscribeRequestTimeout | int | Optional | On non subscribe operations, how long to wait for server response. The value is in seconds. |
FilterExpression | string | Optional | Feature to subscribe with a custom filter expression. |
HeartbeatNotificationOption | PNHeartbeatNotificationOption | Optional | Heartbeat notifications, by default, the SDK will alert on failed heartbeats (equivalent to: PNHeartbeatNotificationOption.FAILURES ). Other options such as all heartbeats ( PNHeartbeatNotificationOption.ALL ) or no heartbeats (PNHeartbeatNotificationOption.NONE ) are supported. |
Origin | string | Optional | Custom Origin if needed. |
ReconnectionPolicy | PNReconnectionPolicy | Optional | Set to PNReconnectionPolicy.LINEAR for automatic reconnects. Use option PNReconnectionPolicy.NONE to disable automatic reconnects. Use option PNReconnectionPolicy.EXPONENTIAL to set exponential retry interval. |
PresenceTimeout | int | Optional | The setting with set the custom presence server timeout. The value is in seconds. |
PresenceInterval | int | Optional | The setting with set the custom presence server timeout along with the custom interval to send the ping back to the server. The value is in seconds. |
Proxy | Proxy | Optional | Instruct the SDK to use a Proxy configuration when communicating with PubNub servers. |
PubnubLog | IPubnubLog | Optional | Pass the instance of a class that implements IPubnubLog to capture logs for troubleshooting. |
UseClassicHttpWebRequest | bool | Optional | Use HttpWebRequest to support ASP.NET/MVC and other IIS hosting applications. |
EnableTelemetry | bool | Optional | Enables the SDK to capture analytics in terms of response time and sends them to PubNub server. It is enabled by default. |
RequestMessageCountThreshold | Number | Optional | PNRequestMessageCountExceededCategory is thrown when the number of messages into the payload is above of requestMessageCountThreshold . |
SuppressLeaveEvents | bool | Optional | When true the SDK doesn't send out the leave requests. |
DedupOnSubscribe | bool | Optional | When true duplicates of subscribe messages will be filtered out when devices cross regions. |
MaximumMessagesCacheSize | int | Optional | It is used with DedupOnSubscribe to cache message size. Default is 100 . |
FileMessagePublishRetryLimit | int | Optional | The number of tries made in case of Publish File Message failure. Default is 5 . |
CryptoModule | AesCbcCryptor(CipherKey) LegacyCryptor(CipherKey) | Optional | None |
CipherKey | This way of setting this parameter is deprecated, pass it to CryptoModule instead. cipher is passed, all communications to/from PubNub will be encrypted. | ||
UseRandomInitializationVector | This way of setting this parameter is deprecated, pass it to CryptoModule instead. true the IV will be random for all requests and not just file upload. When false the IV will be hardcoded for all requests except File Upload.Default false . | ||
Uuid | This 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.
CryptoModule
CryptoModule
provides encrypt/decrypt functionality for messages and files. From the 7.0.1 release on, you can configure how the actual encryption/decryption algorithms work.
Each PubNub SDK is bundled with two ways of encryption: the legacy encryption with 128-bit cipher key entropy and the recommended 256-bit AES-CBC encryption. For more general information on how encryption works, refer to the Message Encryption and File Encryption sections.
If you do not explicitly set the CryptoModule
in your app and have the CipherKey
and UseRandomInitializationVector
params set in PubNub config, the client defaults to using the legacy encryption.
Legacy encryption with 128-bit cipher key entropy
You don't have to change your encryption configuration if you want to keep using the legacy encryption. If you want to use the recommended 256-bit AES-CBC encryption, you must explicitly set that in PubNub config.
CryptoModule
configuration
To configure the CryptoModule
to encrypt all messages/files, you can use the following methods in the C# SDK:
// encrypts using 256-bit AES-CBC cipher (recommended)
// decrypts data encrypted with the legacy and the 256-bit AES-CBC ciphers
pnConfiguration.CryptoModule = new CryptoModule(new AesCbcCryptor("enigma"), new List<ICryptor> { new LegacyCryptor("enigma") })
// encrypts with 128-bit cipher key entropy (legacy)
// decrypts data encrypted with the legacy and the 256-bit AES-CBC ciphers
pnConfiguration.CryptoModule = new CryptoModule(new LegacyCryptor("enigma"), new List<ICryptor> { new AesCbCCryptor("enigma") })
Your client can decrypt content encrypted using either of the modules. This way, you can interact with historical messages or messages sent from older clients while encoding new messages using the more secure 256-bit AES-CBC cipher.
Older SDK versions
Apps built using the SDK versions lower than 7.0.1 will not be able to decrypt data encrypted using the 256-bit AES-CBC cipher. Make sure to update your clients or encrypt data using the legacy algorithm.
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.
// UserId passed during initialization
PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"));
// subscribeKey from Admin Portal
pnConfiguration.SubscribeKey = "SubscribeKey"; // required
// publishKey from Admin Portal (only required if publishing)
pnConfiguration.PublishKey = "PublishKey";
// secretKey (only required for access operations)
pnConfiguration.SecretKey = "SecretKey";
// the cryptography module used for encryption and decryption
pnConfiguration.CryptoModule = new CryptoModule(new AesCbcCryptor("enigma"), new List<ICryptor> { new LegacyCryptor("enigma") })
// Enable Debugging
pnConfigurationr.LogVebosity = PNLogVerbosity.BODY;
// if Access Manager is utilized, client will use this AuthKey in all restricted
// requests
pnConfiguration.AuthKey = "authKey";
show all 30 linesInitialization
Include the code
using PubnubApi;
using PubnubApi.Unity;
Description
This function is used for initializing the PubNub Client API context. You must initialize PubNub before calling any APIs 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 SDK:
new PubNub(pnConfiguration);
Parameter | Type | Required | Description |
---|---|---|---|
pnConfiguration | PNConfiguration | Yes | Refer to 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(new UserId("myUniqueUserId"));
pnConfiguration.PublishKey = "my_pubkey";
pnConfiguration.SubscribeKey = "my_subkey";
pnConfiguration.Secure = true;
Pubnub 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(new UserId("myUniqueUserId"));
pnConfiguration.PublishKey = "my_pubkey";
pnConfiguration.SubscribeKey = "my_subkey";
pnConfiguration.Secure = false;
Pubnub 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(new UserId("myUniqueUserId"));
pnConfiguration.SubscribeKey = "my_subkey";
Pubnub 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(new UserId("myUniqueUserId"));
pnConfiguration.PublishKey = "my_pubkey";
pnConfiguration.SubscribeKey = "my_subkey";
pnConfiguration.Secure = true;
Pubnub 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(new UserId("myUniqueUserId"));
pnConfiguration.PublishKey = "my_pubkey";
pnConfiguration.SubscribeKey = "my_subkey";
pnConfiguration.SecretKey = "my_secretkey";
pnConfiguration.Secure = true;
Pubnub pubnub = new Pubnub(pnConfiguration);
Now that the PubNub object is instantiated the client can access the Access Manager functions. The PubNub object will use the SecretKey
to sign all Access Manager messages to the PubNub Network.
Event Listeners
You can add new listeners to the asset you created as part of the Getting Started instructions or configure them entirely from scratch.
Refer to Getting Started for instructions on how to set up the Unity SDK using assets.
Description
You can be notified of connectivity status, message and presence notifications via the listeners.
Listeners should be added before calling the method.
Add Listeners
using PubnubApi;
using PubnubApi.Unity;
pubnub = new Pubnub(pnConfiguration);
var listener = new SubscribeCallbackListener();
pubnub.AddListener(listener);
listener.onStatus += OnPnStatus;
listener.onMessage += OnPnMessage;
listener.onPresence += OnPnPresence;
listener.onFile += OnPnFile;
listener.onObject += OnPnObject;
listener.onSignal += OnPnSignal;
listener.onMessageAction += OnPnMessageAction;
show all 42 linesRemoving Listeners
protected override void OnDestroy() {
// Use OnDestroy to clean up, e.g. unsubscribe from listeners.
listener.onStatus -= OnPnStatus;
listener.onMessage -= OnPnMessage;
listener.onPresence -= OnPnPresence;
listener.onFile -= OnPnFile;
listener.onObject -= OnPnObject;
listener.onSignal -= OnPnSignal;
listener.onMessageAction -= OnPnMessageAction;
base.OnDestroy();
}
Listener status events
Category | Description |
---|---|
PNNetworkIssuesCategory | A subscribe event experienced connection issues when running. |
PNReconnectedCategory | SDK was able to reconnect to pubnub. |
PNConnectedCategory | SDK subscribed with a new mix of channels (fired every time the channel / channel group mix changed). |
PNAcknowledgmentCategory | Used API reported success with this status category. |
PNAccessDeniedCategory | Request 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. |
PNTimeoutCategory | Used API didn't receive a response from server in time. |
PNDisconnectedCategory | Client unsubscribed from specified real-time data channels. |
PNUnexpectedDisconnectCategory | Subscribe 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. |
PNBadRequestCategory | Request cannot be completed as not all required values have been passed (like subscribe key , publish key ) or passed values are of unexpected data type. |
PNMalformedFilterExpressionCategory | Subscription request cannot be processed as the passed filter expression is malformed and cannot be evaluated. |
PNMalformedResponseCategory | Request received in response non-JSON data. It can be because of an error message from the proxy server (if applicable). |
PNDecryptionErrorCategory | Message Persistence API may return this status category in case if some messages can't be decrypted. |
PNTLSConnectionFailedCategory | TLS handshake issues. In most cases is because of poor network quality and packets loss and delays. |
PNRequestMessageCountExceededCategory | This status event will be fired each time the client receives more messages than the value of RequestMessageCountThreshold, set in PNConfiguration . |
PNReconnectionAttemptsExhausted | In 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. |
PNUnknownCategory | PubNub SDK returns this error for SDK exceptions or when server responds with an error. |
UserId
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 SDK:
UserId
Property | Type | Required | Description |
---|---|---|---|
UserId | string | Yes | UserId to be used as a device identifier. If you don't set the UserId , you won't be able to connect to PubNub. |
config.UserId = new UserId("myUserId");
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 = new PNConfiguration(new UserId("myUniqueUserId"));
config.UserId = new UserId("myUserId");
Get User ID
var currentUserId = pubnub.GetCurrentUserId();
Authentication Key
Setter and getter for users auth key.
Method(s)
AuthKey
Parameter | Type | Required | Description |
---|---|---|---|
AuthKey | string | Yes | If 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 = new PNConfiguration(new UserId("myUniqueUserId"));
pnConfiguration.AuthKey = "authKey";
Get Auth Key
var sampleAuthKey = 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.
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 or get message filters, you can use the following property. To learn more about filtering, refer to the Publish Messages documentation.
Property(s)
FilterExpression
Property | Type | Required | Description |
---|---|---|---|
FilterExpression | string | Yes | PSV2 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 = new PNConfiguration(new UserId("myUniqueUserId"));
pnConfiguration.FilterExpression = "such=wow";
Get Filter Expression
var sampleFilterExp = pnConfiguration.FilterExpression;