PubNub Logo Docs
Support Contact Sales Login Try Our APIs

›First steps

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

    EVENTS & ACTIONS

    • Basics
    • Configure Events & Actions

    FUNCTIONS

    • Basics
    • Development guidelines
    • Functions API
    • Custom integrations

Debug Console
Network Status

Check user presence

PubNub allows you to track the online and offline status of users and devices in real time. This means that you can look up, among other things, who's currently online, when a user has joined/left a channel or which channels a user is subscribed to.

The code below will print to the console a list of all users who are online on the chats.public.release_announcements channel.

JavaScript
Swift
Objective-C
Android
C#
Python

Go to SDK

pubnub.hereNow(
{
channels: ["chats.public.release_announcements"]
},
function (status, response) {
console.log(status, response);
}
);

Go to SDK

pubnub.hereNow(on: ["chats.public.release_announcements"]),
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.public.release_announcements"]
withVerbosity:PNHereNowState
completion:^(PNPresenceChannelHereNowResult *result, PNErrorStatus *status) {
// parse the HereNow result parameter
}];

Go to SDK

pubnub.hereNow()
.channels(Arrays.asList("chats.public.release_announcements"))
.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.public.release_announcements"})
.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.public.release_announcements")\
.include_state(True)\
.pn_async(here_now_callback)

Checking presence is based on receiving presence events which are sent automatically from the PubNub servers when a user's state changes. You can react to these events by handling them using a handler dedicated for presence events.

Presence events aren't sent on the channel where a change in presence happens. They're sent on a presence channel, which is a helper channel that gets created automatically for every regular channel. As it behaves like a normal channel, to receive the data sent to it, you must subscribe to the presence channel.

If you know you will be interested in real-time presence changes, it's best to do it when you subscribe to the regular channel.

JavaScript
Swift
Objective-C
Android
C#
Python

Go to SDK

// subscribe to a single channel without presence
pubnub.subscribe({channels: ["chats_inbox.user_1905"]});

// subscribe to multiple channels with presence
pubnub.subscribe({
channels: [
"chats_guilds.mages_guild",
"alerts.system",
"geolocation.data"
],
withPresence: true
});

Go to SDK

pubnub.subscribe(
to: ["chats.public.release_announcements"],
withPresence: true
)

Go to SDK

[self.pubnub subscribeToChannels: @[@"chats_guilds.mages_guild", @"chats_inbox.user_1905"] withPresence:YES];

Go to SDK

pubnub.subscribe()
.channels(Arrays.asList("chats.public.release_announcements"))
.withPresence().execute();

Go to SDK

pubnub.Subscribe<string>()
.Channels(new string[] {"chats.public.release_announcements"})
.WithPresence()
.Execute();

Go to SDK

pubnub.subscribe()\
.channels("chats.public.release_announcements")\
.with_presence()\
.execute()

As a part of user presence, you can set a custom dynamic state, like current score or mood indicator, for the users in your channels. However, this state persists only as long as the user is subscribed to a channel. Once the user disconnects, that custom data is lost.

If you don't want to lose any additional data about your users and channels, consider adding metadata.

← Retrieve old messagesAdd custom metadata →
© PubNub Inc. - Privacy Policy