Check user presence
PubNub lets you track the online and offline status of users and devices in real time. You can see who is online, when a user joins or leaves a channel, and which channels a user is subscribed to. Learn the basics in Presence fundamentals.
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).
Before you begin, make sure you have initialized PubNub with your keys. The code below prints 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
1pubnub.hereNow(
2 {
3 channels: ["chats.public.release_announcements"]
4 },
5 function (status, response) {
6 console.log(status, response);
7 }
8);
1pubnub.hereNow(on: ["chats.public.release_announcements"]),
2 includeUUIDs: true, also: true { result in
3 switch result {
4 case let .success(response):
5 print("Successful hereNow Response: \(response)")
6
7 case let .failure(error):
8 print("Failed hereNow Response: \(error.localizedDescription)")
9 }
10})
1[self.pubnub hereNowForChannel: @[@"chats.public.release_announcements"]
2 withVerbosity:PNHereNowState
3 completion:^(PNPresenceChannelHereNowResult *result, PNErrorStatus *status) {
4 // parse the HereNow result parameter
5}];
1pubnub.hereNow()
2 .channels(Arrays.asList("chats.public.release_announcements"))
3 .includeState(true)
4 .async(result -> {
5 result.onSuccess(res -> {
6 for (PNHereNowChannelData channelData : res.getChannels().values()) {
7 System.out.println("---");
8 System.out.println("channel:" + channelData.getChannelName());
9 System.out.println("occupancy: " + channelData.getOccupancy());
10 System.out.println("occupants:");
11
12 for (PNHereNowOccupantData occupant : channelData.getOccupants()) {
13 System.out.println("uuid: " + occupant.getUuid()
14 + " state: " + occupant.getState());
15 }
show all 20 lines1pubnub.HereNow()
2 .Channels(new string[] {"chats.public.release_announcements"})
3 .IncludeState(true)
4 .Execute(new PNHereNowResultEx((result, status) => {
5 if (status.Error) {
6 Console.WriteLine("HereNow error: " + status);
7 }
8 else if (result.Channels != null && result.Channels.Count > 0) {
9 foreach (KeyValuePair<string, PNHereNowChannelData> kvp in result.Channels) {
10 PNHereNowChannelData channelData = kvp.Value;
11 Console.WriteLine("---");
12 Console.WriteLine("channel:" + channelData.ChannelName);
13 Console.WriteLine("occupancy:" + channelData.Occupancy);
14 Console.WriteLine("Occupants:");
15
show all 27 lines1def here_now_callback(result, status):
2 if status.is_error():
3 print("here_now error: %s" % status)
4 return
5
6 for channel_data in result.channels:
7 print("---")
8 print("channel: %s" % channel_data.channel_name)
9 print("occupancy: %s" % channel_data.occupancy)
10
11 print("occupants: %s" % channel_data.channel_name)
12
13 for occupant in channel_data.occupants:
14 print("uuid: %s, state: %s" % (occupant.uuid, occupant.state))
15
show all 19 lines1var result = await pubnub.hereNow(channels: {'chats.public.release_announcements'});
1pubnub.hereNow(
2 channels = listOf("chats.public.release_announcements"),
3 includeUUIDs = true,
4 includeState = true
5).async { result, status ->
6 if (status.error) {
7 // handle error
8 status.exception?.printStackTrace()
9 return@async
10 }
11 result!!.channels.values.forEach { channelData ->
12 println("---")
13 println("Channel: ${channelData.channelName}")
14 println("Occupancy: ${channelData.occupancy}")
15 println("Occupants:")
show all 20 linesPresence relies on presence events that PubNub sends automatically when a user’s state changes. You can react to these events by adding a handler dedicated to presence events.
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).
PubNub sends presence events on a presence channel, not on the channel where the change happens. A presence channel is created automatically for every regular channel.
If you need real‑time presence changes, enable presence when you subscribe to the regular channel.
- JavaScript
- Swift
- Objective-C
- Java
- C#
- Python
- Dart
- Kotlin
1// subscribe to a single channel without presence
2pubnub.subscribe({channels: ["chats_inbox.user_1905"]});
3
4// subscribe to multiple channels with presence
5pubnub.subscribe({
6 channels: [
7 "chats_guilds.mages_guild",
8 "alerts.system",
9 "geolocation.data"
10 ],
11 withPresence: true
12});
1pubnub.subscribe(
2 to: ["chats.public.release_announcements"],
3 withPresence: true
4)
1[self.pubnub subscribeToChannels: @[@"chats_guilds.mages_guild", @"chats_inbox.user_1905"] withPresence:YES];
1pubnub.subscribe()
2 .channels(Arrays.asList("chats.public.release_announcements"))
3 .withPresence().execute();
1Subscription subscription1 = pubnub.Channel("chats.public.release_announcements").Subscription(SubscriptionOptions.ReceivePresenceEvents)
2
3subscription1.Subscribe<object>()
1subscription = pubnub.channel_group('chats.public.release_announcements').subscription(with_presence = True)
2subscription.subscribe()
1var channel = "chats.public.release_announcements";
2var subscription = pubnub.subscribe(channels: {channel}, withPresence: true);
1pubnub.subscribe(
2 channels = listOf("chats.public.release_announcements")
3 withPresence = true
4)
As part of user presence, you can set a custom dynamic state, such as a score or mood indicator, for users in your channels. This state persists only while the user is subscribed to a channel. When the user disconnects, the custom data is removed.
If you don't want to lose any additional data about your users and channels, consider adding metadata.