Presence Basics
Presence gives you visibility into who is currently subscribed to a channel.
Presence monitors channel subscribers and delivers real-time status information. You can:
- 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 enable Presence on a keyset in the Admin Portal, you can subscribe to presence events. PubNub automatically creates presence equivalents of all channels. Presence channels reuse the base channel name with the -pnpres
suffix and track all presence events about users.
Subscription with Presence
To receive Presence events, you subscribe with Presence and have Presence enabled on your keyset. Make sure you configure Presence to track Presence-related events for all or selected channels (through Presence Management rules).
Configuration
To use Presence, enable and configure it on a selected app keyset in the Admin Portal.
Public Admin Portal demo
Want to browse through the Admin Portal without creating an account? Explore it through the Public Demo that shows examples of most PubNub features for transport and logistics use case.
When you create a keyset in the Admin Portal, Presence is enabled by default.
Choose how you want to configure Presence:
-
Selected channels only (recommended) — disable Presence events by default.
You selectively enable Presence for specific channels using rules in Presence Management. Until then, you will not receive Presence-related events such as join, leave, or presence state changes.
-
All channels — track Presence-related events for every channel (may increase cost).
Presence offers the following options:
Option | Description |
---|---|
Announce Max | The maximum channel occupancy above which specific events are reduced. When occupancy exceeds this value, join , leave , and timeout Presence events are replaced by recurring interval events that report channel occupancy. |
Interval | The cadence (in seconds) for interval events when Announce Max is exceeded. |
Presence Deltas | Adds two fields to each interval event: lists of users who joined and who left since the last update. |
Generate Leave on TCP FIN or RST | Detects network-layer connection termination and reports a leave event instead of a timeout event (for example, when a browser tab closes or an app is force quit). Generates additional billable events. |
Stream Filtering | Filters Presence events at the client. You receive only relevant events on the Presence channel (for example, join events for a specific User ID). |
Active Notice Channel | Sends notifications when a channel switches between active (has subscribers) and inactive (no subscribers). |
Debounce | The number of seconds to wait before allowing a join event after an explicit leave . Helps smooth out rapid state changes. |
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 IDs, including clients' state data, and the total occupancy of the channel using the Here Now API.
Once the current state has been fetched, your app can rely on presence events to keep the user state up to date. Go to Presence Events to learn more.
Cache response time
The hereNow()
method 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
Now that you know how to fetch the current state, Presence events keep that state in sync. Presence events are sent as users come online or go offline. For details on event types and how to receive them in your client, see Presence Events.