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.
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.
The code below will print to the console a list of all users who are online on the chats.public.release_announcements
channel.
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.
- JavaScript
- Swift
- Objective-C
- Java
- C#
- Python
- Dart
- Kotlin
pubnub.hereNow(
{
channels: ["chats.public.release_announcements"]
},
function (status, response) {
console.log(status, response);
}
);
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)")
}
})
[self.pubnub hereNowForChannel: @[@"chats.public.release_announcements"]
withVerbosity:PNHereNowState
completion:^(PNPresenceChannelHereNowResult *result, PNErrorStatus *status) {
// parse the HereNow result parameter
}];
pubnub.hereNow()
.channels(Arrays.asList("chats.public.release_announcements"))
.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("uuid: " + occupant.getUuid()
+ " state: " + occupant.getState());
}
show all 20 linespubnub.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:");
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("uuid: %s, state: %s" % (occupant.uuid, occupant.state))
show all 19 linesvar result = await pubnub.hereNow(channels: {'chats.public.release_announcements'});
pubnub.hereNow(
channels = listOf("chats.public.release_announcements"),
includeUUIDs = true,
includeState = true
).async { result, status ->
if (status.error) {
// handle error
status.exception?.printStackTrace()
return@async
}
result!!.channels.values.forEach { channelData ->
println("---")
println("Channel: ${channelData.channelName}")
println("Occupancy: ${channelData.occupancy}")
println("Occupants:")
show all 20 linesChecking 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 to presence events.
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 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.
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
- Java
- C#
- Python
- Dart
- Kotlin
// 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
});
pubnub.subscribe(
to: ["chats.public.release_announcements"],
withPresence: true
)
[self.pubnub subscribeToChannels: @[@"chats_guilds.mages_guild", @"chats_inbox.user_1905"] withPresence:YES];
pubnub.subscribe()
.channels(Arrays.asList("chats.public.release_announcements"))
.withPresence().execute();
Subscription subscription1 = pubnub.Channel("chats.public.release_announcements").Subscription(SubscriptionOptions.ReceivePresenceEvents)
subscription1.Subscribe<object>()
subscription = pubnub.channel_group('chats.public.release_announcements').subscription(with_presence = True)
subscription.subscribe()
var channel = "chats.public.release_announcements";
var subscription = pubnub.subscribe(channels: {channel}, withPresence: true);
pubnub.subscribe(
channels = listOf("chats.public.release_announcements")
withPresence = true
)
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.