PubNub Logo Docs
Support Contact Sales Login Try Our APIs

›User presence

Collapse all
Dark mode

Home

  • Home

First steps

  • Set up your account
  • Get the SDK
  • Initialize PubNub
  • Identify users and devices
  • Send messages
  • Receive messages
  • Retrieve old messages
  • Check user presence
  • Add custom metadata
  • Manage access
  • Add serverless business logic
  • Send push notifications

Setup

  • PubNub account
  • Application
  • Users & devices
  • Connection management
  • Data security
  • Data persistence
  • API limits

Chat

  • In-App Chat

SDKs

  • SDKs

Messages

  • Publish
  • Receive
  • Actions
  • Payload type conventions

Channels

  • Basics
  • Subscription
  • Naming conventions

User presence

  • Basics
  • Events
  • State
  • Webhooks

Metadata

  • Channel
  • User
  • Membership

Message Persistence

  • Message Persistence

File sharing

  • File sharing

Access management

  • Manage access

Push notifications

  • Basics
  • iOS
  • Android
  • Troubleshooting

Best practices

  • Architectural choices
  • Message aggregation
  • Friend list & status feed
  • Troubleshooting
  • Migration guides

Serverless processing

  • Basics
  • Development guidelines
  • Functions API
  • Custom integrations

Debug Console
Network Status

Presence Basics

Presence monitors the subscribers of channels and delivers information on their real-time status.

It also lets you:

  • Measure channel occupancy.
  • Monitor dynamic custom state information, like profile info, typing notices, current location, or mood indicators.
  • Use webhooks to have PubNub notify your server whenever presence events occur on any channel for your keys.

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.

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 clients UUIDs, 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 the Presence Events to learn more.

JavaScript
Swift
Objective-C
Android
C#
Python

Go to SDK

pubnub.hereNow(
{
channels: ["chats.room1", "chats.room2"],
includeState: true
},
function (status, response) {
console.log(status, response);
}
);

Go to SDK

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)")
}
})

Go to SDK

[self.pubnub hereNowForChannel: @[@"chats.room1", "chats.room2"]
withVerbosity:PNHereNowState
completion:^(PNPresenceChannelHereNowResult *result, PNErrorStatus *status) {
// parse the HereNow result parameter
}];

Go to SDK

pubnub.hereNow()
.channels(Arrays.asList("chats.room1", "chats.room2"))
.includeState(true)
.async(new PNCallback<PNHereNowResult>() {
@Override
public void onResponse(PNHereNowResult result, PNStatus status) {
if (status.isError()) {
// handle error
return;
}

for (PNHereNowChannelData channelData : result.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("uuid: " + occupant.getUuid()
+ " state: " + occupant.getState());
}
}
}
});

Go to SDK

pubnub.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:");

if (channelData.Occupants != null && channelData.Occupants.Count > 0) {
for (int index = 0; index < channelData.Occupants.Count; index++) {
PNHereNowOccupantData occupant = channelData.Occupants[index];
Console.WriteLine(string.Format("uuid: {0}", occupant.Uuid));
Console.WriteLine(string.Format("state:{1}", (occupant.State != null) ?
pubnub.JsonPluggableLibrary.SerializeToJsonString(occupant.State) : ""));
}
}
}
}
}
));

Go to SDK

def 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("uuid: %s, state: %s" % (occupant.uuid, occupant.state))

pubnub.here_now()\
.channels("chats.room1", "chats.room2")\
.include_state(True)\
.pn_async(here_now_callback)

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
Android
C#
Python

Go to SDK

pubnub.whereNow({uuid: pubnub.uuid},
function (status, response) {
// handle status, response
}
);

Go to SDK

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)")
}
}

Go to SDK

[self.pubnub whereNowUUID:self.pubnub.uuid withCompletion:
^(PNPresenceWhereNowResult *result, PNErrorStatus *status) {
if (!status) {
NSLog(status);
}
else {
NSLog(result);
}
}];

Go to SDK

pubnub.whereNow()
.async(new PNCallback<PNWhereNowResult>() {
@Override
public void onResponse(PNWhereNowResult result, PNStatus status) {
if (status.isError()) {
System.outprintln(status);
}
else {
System.outprintln(result);
}
}
});

Go to SDK

pubnub.WhereNow()
.Execute(new PNWhereNowResultExt((result, status) => {
if (status.isError) {
Console.WriteLine(status.ErrorData.Information);
}
else {
Console.WriteLine(result);
}
}
));

Go to SDK

envelope = pubnub.where_now().sync()
← Naming conventionsEvents →
  • Get Online Users in Channel
  • Get Subscribed Channels for User
© PubNub Inc. - Privacy Policy