Presence Basics
Presence gives you visibility into who is currently subscribed to a channel.
In other words, it monitors the subscribers of channels and delivers information on their real-time status. It also lets you:
- Measure channel occupancy.
- Monitor and add dynamic custom state information, like profile info, typing indicators, or current location.
- Use Events & Actions to have PubNub notify your server whenever presence events occur.
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.
When you have Presence enabled on your keyset in the Admin Portal, PubNub automatically creates additional presence equivalents of all channels. These presence channels are named after the main ones but contain an additional -pnpres
suffix. Their purpose is to track all presence events about users.
Subscription with Presence
You must create a subscription with Presence enabled to receive Presence events. For more information, refer to each SDK's Publish and Subscribe documentation.
Presence Management
If you want to track Presence only for the selected channels and channel groups, create Presence rules in the Admin Portal as part of the BizOps Workspace.
Configuration
To use Presence, you must enable and configure it on a chosen app's keyset in the Admin Portal.
Option | Description |
---|---|
Announce Max | A maximum number of occupants in a channel after which you want to receive specific Presence events less frequently. Suppose the number of clients subscribed to a channel goes above this value. In that case, you will no longer receive join , leave , or timeout Presence events, but instead, you'll receive a recurring interval event informing about channel occupancy. |
Interval | The option that relates to the Announce Max setting and specifies how often (in seconds) the interval event fires. |
Presence Deltas | While the interval event specifies how many people subscribed to the channel in a specified amount of time, you may want to know who has joined or left the channel since the last update. Using this option, you'll get two additional fields for every interval event: lists of users who joined and those who left the channel. |
Generate Leave on TCP FIN or RST | This option will detect the connection termination of a network layer and report it as a PubNub leave event. A leave event instead of a timeout event will be generated when a browser tab is closed or an application is force quitted. |
Stream Filtering | The option that lets you filter out the Presence events at the client level to receive to the Presence channel only the relevant events (like join events only for a particular User ID). |
Active Notice Channel | For some use cases, you are not concerned about how many occupants you have in the channel or who they are. You only care whether a channel has active subscribers or not. If nobody is subscribed to a channel, you refer to it as an inactive channel, and if there are subscribers, the channel is active. This option lets you specify a channel to receive notifications about channels as their active or inactive state changes. |
Debounce | A number of seconds to wait before allowing a join event to fire after an explicit leave event. It's a way of smoothing out any rapidly changing state caused by network issues or even deliberate action on the user's part. |
Get Online Users in Channel
When a client opens the app, it's often required to discover what other users are already subscribed to that channel (for example, to construct a chat room's online friends list). You can obtain a list of client User IDsUser ID
UTF-8 encoded, unique string of up to 92 characters used to identify a single client (end user, device, or server) that connects to PubNub.
Once the current state has been fetched, your app can rely on presence events to keep the user state up to date. Go to the Presence Events to learn more.
note
hereNow()
cache response timeNote that hereNow()
has a 3 second response cache time.
- JavaScript
- Swift
- Objective-C
- Java
- C#
- Python
pubnub.hereNow(
{
channels: ["chats.room1", "chats.room2"],
includeState: true
},
function (status, response) {
console.log(status, response);
}
);
pubnub.hereNow(on: ["chats.room1", "chats.room2"]), and: [],
includeUUIDs: true, also: true { result in
switch result {
case let .success(response):
print("Successful hereNow Response: \(response)")
case let .failure(error):
print("Failed hereNow Response: \(error.localizedDescription)")
}
})
[self.pubnub hereNowForChannel: @[@"chats.room1", "chats.room2"]
withVerbosity:PNHereNowState
completion:^(PNPresenceChannelHereNowResult *result, PNErrorStatus *status) {
// parse the HereNow result parameter
}];
pubnub.hereNow()
.channels(Arrays.asList("chats.room1", "chats.room2"))
.includeState(true)
.async(result -> {
result.onSuccess(res -> {
for (PNHereNowChannelData channelData : res.getChannels().values()) {
System.out.println("---");
System.out.println("channel:" + channelData.getChannelName());
System.out.println("occupancy: " + channelData.getOccupancy());
System.out.println("occupants:");
for (PNHereNowOccupantData occupant : channelData.getOccupants()) {
System.out.println("userId: " + occupant.getUuid()
+ " state: " + occupant.getState());
}
show all 20 linespubnub.HereNow()
.Channels(new string[] {"chats.room1", "chats.room2"})
.IncludeState(true)
.Execute(new PNHereNowResultEx((result, status) => {
if (status.Error) {
Console.WriteLine("HereNow error: " + status);
}
else if (result.Channels != null && result.Channels.Count > 0) {
foreach (KeyValuePair<string, PNHereNowChannelData> kvp in result.Channels) {
PNHereNowChannelData channelData = kvp.Value;
Console.WriteLine("---");
Console.WriteLine("channel:" + channelData.ChannelName);
Console.WriteLine("occupancy:" + channelData.Occupancy);
Console.WriteLine("Occupants:");
show all 27 linesdef here_now_callback(result, status):
if status.is_error():
print("here_now error: %s" % status)
return
for channel_data in result.channels:
print("---")
print("channel: %s" % channel_data.channel_name)
print("occupancy: %s" % channel_data.occupancy)
print("occupants: %s" % channel_data.channel_name)
for occupant in channel_data.occupants:
print("user_id: %s, state: %s" % (occupant.user_id, occupant.state))
show all 19 linesCustom user state
You can add custom state information to the users in your application. For more details, refer to Presence State.
Get Subscribed Channels for User
Sometimes it may be necessary for the client app to confirm the channels to which it's currently subscribed. Though this is rarely necessary to do this, except for possibly when you're testing and troubleshooting your app. This can be accomplished with the Where Now API.
- JavaScript
- Swift
- Objective-C
- Java
- C#
- Python
pubnub.whereNow({uuid: pubnub.uuid},
function (status, response) {
// handle status, response
}
);
pubnub.whereNow(for: pubnub.uuid) { result in
switch result {
case let .success(response):
print("Successful WhereNow Response: \(response)")
case let .failure(error):
print("Failed WhereNow Response: \(error.localizedDescription)")
}
}
[self.pubnub whereNowUUID:self.pubnub.uuid withCompletion:
^(PNPresenceWhereNowResult *result, PNErrorStatus *status) {
if (!status) {
NSLog(status);
}
else {
NSLog(result);
}
}];
pubnub.whereNow()
.async(result -> { /* check result */ });
pubnub.WhereNow()
.Execute(new PNWhereNowResultExt((result, status) => {
if (status.isError) {
Console.WriteLine(status.ErrorData.Information);
}
else {
Console.WriteLine(result);
}
}
));
envelope = pubnub.where_now().sync()
Presence events
Presence events are sent as users come online or go offline from the application. For more details on what they are and how you can receive these events directly from your client, refer to Presence Events.