Initialize PubNub
Before you start calling PubNub APIs, you must initialize the PubNub object in your app. This initialization uses the publish and subscribe keys you got from the Admin Portal and allows you to work with PubNub functionality. The PubNub object is also where you configure the behavior of the client, such as what to do when a connection is interrupted or whether to encrypt messages.
You only need to provide subscribeKey
and userId
if you want your app to receive messages. If you plan on sending messages, you must configure publishKey
as well. There are other ways of initializing PubNub, depending on the features you want to use.
note
userId
descriptiveIt's up to you to define a userId
, which is a UTF-8 encoded string of up to 92 characters used to identify the device that connects to PubNub.
Check out how easy it is:
- JavaScript
- Node.js
- Swift
- Objective-C
- Java
- C#
- Python
- Dart
- Kotlin
var pubnub = new PubNub({
publishKey: "myPublishKey",
subscribeKey: "mySubscribeKey",
userId: "myUniqueUserId"
});
const pubnub = new PubNub({
subscribeKey: 'mySubscribeKey',
publishKey: 'myPublishKey',
userId: 'myUniqueUserId',
});
import PubNubSDK
var pnconfig = PubNubConfiguration(
publishKey: "myPublishKey",
subscribeKey: "mySubscribeKey"
)
pnconfig.userId = "myUniqueUserId"
let pubnub = PubNub(configuration: pnconfig)
PNConfiguration *pnconfig = [PNConfiguration configurationWithPublishKey:@"myPublishKey"
subscribeKey:@"mySubscribeKey"];
pnconfig.uuid = "myUniqueuuid";
PubNub *pubnub = [PubNub clientWithConfiguration:pnconfig];
PNConfiguration.Builder configBuilder = PNConfiguration.builder(new UserId("yourUserId"), "yourSubscribeKey");
configBuilder.publishKey("myPublishKey");
PubNub pubNub = PubNub.create(configBuilder.build());
PNConfiguration pnconfig = new PNConfiguration();
pnconfig.PublishKey = "myPublishKey";
pnconfig.SubscribeKey = "mySubscribeKey";
pnconfig.UserId = "myUniqueUserId";
Pubnub pubnub = new Pubnub(pnconfig);
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub
pnconfig = PNConfiguration()
pnconfig.publish_key = "myPublishKey"
pnconfig.subscribe_key = "mySubscribeKey"
pnconfig.user_id = "myUniqueUserId"
pubnub = PubNub(pnconfig)
var pubnub = PubNub(
defaultKeyset:
Keyset(subscribeKey: 'mySubscribeKey', publishKey: 'myPublishKey', userId: UserId('myUniqueUserId')));
val builder = PNConfiguration.builder(UserId("myUniquesUserID"), "subscribeKey") {
publishKey = "publishKey"
}
val pubnub = PubNub.create(builder.build())
User ID / UUID
User ID is also referred to as UUID
/uuid
in some APIs and server responses but holds the value of the userId
parameter you set during initialization.
You don't have to create a separate PubNub object every time you want to send or receive a message. After the initialization, subscribeKey
, publishKey
, and userId
are reused for all operations.
Let's look into the userId
parameter a bit more.