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

    EVENTS & ACTIONS

    • Basics
    • Configure Events & Actions

    FUNCTIONS

    • Basics
    • Development guidelines
    • Functions API
    • Custom integrations

Debug Console
Network Status

Presence State

Clients can set dynamic custom state for their users on one or more channels. This custom state persists on a channel as long as the user stays subscribed to that channel. Some examples of custom state are to add your score, game state, or location in an application if it changes frequently.

State is transient data (it's not persisted anywhere). When the client disconnects, the state data is lost. If you require a client's state to be restored on reconnect, be sure to cache that data locally to the client. If you wish to persist data forever, please refer to the Objects feature.

PubNub also triggers presence state-change events anytime the user's state is modified. Clients can receive these events by subscribing to presence channels. Refer to Presence Events for more details.

Setting Presence State

You can set state data for a UUID on a given channel(s) or channel group(s). The UUID is the current client's UUID when this API is invoked. When setting state on a channel group, it propagates that state to all channels contained in that channel group.

JavaScript
Swift
Objective-C
Android
C#
Python

Go to SDK

pubnub.setState(
{
state: {"mood":"pumped", "isTyping":false},
channels: ["chats.room1"],
channelGroups: ["cg_user123_friends"]
},
function (status, response) {
if (status.isError) {
console.log(status);
}
else {
console.log(response);
}
}
);

Go to SDK

pubnub.setPresence(
state: ["mood": "pumped", "workingFrom": "Home"],
on: ["chats.room1"],
and: ["cg_user123_friends"]
) { result in
switch result {
case let .success(response):
print("Successful Set State Response: \(response)")

case let .failure(error):
print("Failed Set State Response: \(error.localizedDescription)")
}
}

Go to SDK

[self.pubnub setState: @{@"mood": @"pumped", @"workingFrom": @"Home"}
forUUID:self.pubnub.uuid onChannel: @"chats.room1"
withCompletion:^(PNClientStateUpdateStatus *status) {
// handle status
}];

Go to SDK

JsonObject state = new JsonObject();
state.addProperty("mood", "pumped");
state.addProperty("workingFrom", "Home");

pubnub.setPresenceState()
.channels(Arrays.asList("chats.room1"))
.channelGroups(Arrays.asList("cg_user123_friends"))
.state(state).async(new PNCallback<PNSetStateResult>() {
@Override
public void onResponse(final PNSetStateResult result, PNStatus status) {
if (status.isError()) {
System.out.println(status);
}
else {
System.out.println(result);
}
}
});

Go to SDK

Dictionary<string, object> state = new Dictionary<string, object>();
state.Add("mood", "pumped");
state.Add("workingFrom", "Home");

pubnub.SetPresenceState()
.Channels(new string[] {"chats.room1"})
.ChannelGroups(new string[] {"cg_user123_friends"})
.State(myState)
.Execute(new PNSetStateResultExt((result, status) => {
if (status.IsError()) {
Console.WriteLine("SetPresenceState error:" + status);
}
else {
Console.WriteLine("SetPresenceState success:" + result);
}
}
));

Go to SDK

my_state = {"mood": "pumped", "workingFrom": "Home"}

envelope = pubnub.set_state()\
.channels(["chats.room1"]) \
.channel_groups(["cg_user123_friends"])\
.state(my_state)\
.sync()

When you set state for a client, the existing state is overwritten. Therefore, if you need to update part of the state, you must pass the complete state data payload. For this reason, it's best to keep your state data payloads from getting too large.

Getting Presence State

You can get state data for any client on a given channel(s) or channel group(s) user the Get State API. This is useful to get the state of other clients based on their UUID.

JavaScript
Swift
Objective-C
Android
C#
Python

Go to SDK

pubnub.getState(
{
uuid: "anotherClientUUID",
channels: ["chats.room1"],
channelGroups: ["cg_user123_friends"]
},
function (status, response) {
// handle status, response
}
);

Go to SDK

pubnub.getPresenceState(
for: "anotherClientUUID",
on: ["chats.room1"],
and: ["cg_user123_friends"]
) { result in
switch result {
case let .success(response):
print("Successful Get State Response: \(response)")

case let .failure(error):
print("Failed Get State Response: \(error.localizedDescription)")
}
}

Go to SDK

 [self.pubnub stateForUUID:@"anotherClientUUID" onChannel:@"chats.room1"
withCompletion:^(PNChannelClientStateResult *result, PNErrorStatus *status) {

if (!status) {

}
else {

}
}];

Go to SDK

pubnub.getPresenceState()
.channels(Arrays.asList("chats.room1"))
.channelGroups(Arrays.asList("cg_user123_friends"))
.uuid("anotherClientUUID")
.async(new PNCallback<PNGetStateResult>() {
@Override
public void onResponse(PNGetStateResult result, PNStatus status) {
if (status.isError()) {
System.out.println(status);
}
else {
System.out.println(result);
}
}
});

Go to SDK

pubnub.GetPresenceState()
.Channels(new string[] {"chats.room1"})
.Uuid(clientUUID)
.Execute(new PNGetStateResultExt((result, status) => {
if (status.IsError()) {
Console.WriteLine("GetPresenceState error:" + status);
}
else {
Console.WriteLine("GetPresenceState success:" + result);
}
}
));

Go to SDK

envelope = pubnub.get_state()\
.uuid("anotherClientUUID")\
.channels(["chats.room1"])\
.sync()
← EventsWebhooks →
  • Setting Presence State
  • Getting Presence State
© PubNub Inc. - Privacy Policy