All chat applications have a notion of a user. It's important to be able to uniquely identify users as they interact with the PubNub Network. Usually, a user is a human end user—a person using an app to interact with a system (via a laptop, phone, tablet, or kiosk).
You use a User ID to uniquely identify each user on the system. Users can connect from multiple devices, such as phones, tablets, desktops, etc., using the same User ID. If a user is connected from multiple devices simultaneously, they will receive the same messages on each device.
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.
Start by initializing a PubNub object with publishKey, subscribeKey, and userId as required fields. The userId is a string of maximum 92 characters that represents a user in your application.
Your publish and subscribe keys are available in your PubNub Account. Go to the Admin Portal to create your free account.
userId is required
Setting the userId parameter is required to establish a connection to PubNub, ensure that your billing is accurate, and for other features like presence and storage to work as expected.
JavaScript
Java
Swift
Objective-C
1const pubnub =newPubNub({ 2subscribeKey:"mySubscribeKey", 3publishKey:"myPublishKey", 4userId:"john-doe", 5autoNetworkDetection:true,// enable for non-browser environment automatic reconnection 6restore:true,// enable catchup on missed messages 7});
Events are received in your app using listeners. These listeners allows a single point to receive messages, signals, and presence events. Each event type has its own handler to receive them where you implement your custom app logic to perform actions on events.
The following handlers are available to you:
Handler
Description
Status
Receives events when the client successfully connects (subscribes), or reconnects (in case of connection issues) to channels.
Message
Receives all messages published to all the channels subscribed by the client. The event payload will contain the published message data, publish timetoken, the User ID of the client that published the message and more.
Signal
Receives all signals that are sent to any channels subscribed by the client. The event payload will contain the signal data, signal timetoken, the User ID of the client that published the message and more.
Presence
Receives all presence events that are triggered on any channels subscribed by the client. The event payload will contain the presence event type (join, leave, timeout, state-change), timetoken of the action, the User ID of the client that caused the event, state data (if applicable) and more.
MessageAction
Receives all events when existing messages are annotated (by an action) for any channels subscribed by the client. The event payload will contain the User ID that acted on the message, message reaction type (such as an emoji reaction), timetoken of the annotated message, timetoken of the action, action value and more.
Objects
Receives all objects events that are emitted when a channel, channel membership, or user metadata is created, updated or removed.
JavaScript
Java
Swift
Objective-C
Unity
1pubnub.addListener({ 2message:function(m){ 3// handle message 4var channelName = m.channel;// The channel to which the message was published 5var channelGroup = m.subscription;// The channel group or wildcard subscription match (if exists) 6var pubTT = m.timetoken;// Publish timetoken 7var msg = m.message;// The Payload 8var publisher = m.publisher;//The Publisher 9}, 10presence:function(p){ 11// handle presence 12var action = p.action;// Can be join, leave, state-change, or timeout 13var channelName = p.channel;// The channel to which the message was published 14var occupancy = p.occupancy;// Number of users subscribed to the channel 15var state = p.state;// User State 16var channelGroup = p.subscription;// The channel group or wildcard subscription match (if exists) 17var publishTime = p.timestamp;// Publish timetoken 18var timetoken = p.timetoken;// Current timetoken 19var uuid = p.uuid;// UUIDs of users who are subscribed to the channel 20}, 21signal:function(s){ 22// handle signal 23var channelName = s.channel;// The channel to which the signal was published 24var channelGroup = s.subscription;// The channel group or wildcard subscription match (if exists) 25var pubTT = s.timetoken;// Publish timetoken 26var msg = s.message;// The Payload 27var publisher = s.publisher;//The Publisher 28}, 29objects:(objectEvent)=>{ 30var channel = objectEvent.channel;// The channel 31var channelGroup = objectEvent.subscription;// The channel group 32var timetoken = objectEvent.timetoken;// The event timetoken 33var publisher = objectEvent.publisher;// The User ID that triggered this event 34var event = objectEvent.event;// The event name that occurred 35var type = objectEvent.type;// The event type that occurred 36var data = objectEvent.data;// The event data that occurred 37}, 38messageAction:function(ma){ 39// handle message reaction 40var channelName = ma.channel;// The channel to which the message was published 41var publisher = ma.publisher;//The Publisher 42var event = ma.message.event;// message reaction added or removed 43var type = ma.message.data.type;// message reaction type 44var value = ma.message.data.value;// message reaction value 45var messageTimetoken = ma.message.data.messageTimetoken;// The timetoken of the original message 46var actionTimetoken = ma.message.data.actionTimetoken;// The timetoken of the message reaction 47}, 48file:function(event){ 49const channelName = event.channel;// Channel to which the file belongs 50const channelGroup = event.subscription;// Channel group or wildcard subscription match (if exists) 51const publisher = event.publisher;// File publisher 52const timetoken = event.timetoken;// Event timetoken 53const message = event.message;// Optional message attached to the file 54const fileId = event.file.id;// File unique id 55const fileName = event.file.name;// File name 56const fileUrl = event.file.url;// File direct URL 57}, 58status:function(s){ 59var affectedChannelGroups = s.affectedChannelGroups;// The channel groups affected in the operation, of type array. 60var affectedChannels = s.affectedChannels;// The channels affected in the operation, of type array. 61var category = s.category;//Returns PNConnectedCategory 62var operation = s.operation;//Returns PNSubscribeOperation 63var lastTimetoken = s.lastTimetoken;//The last timetoken used in the subscribe request, of type long. 64var currentTimetoken = s.currentTimetoken;//The current timetoken fetched in the subscribe response, which is going to be used in the next request, of type long. 65var subscribedChannels = s.subscribedChannels;//All the current subscribed channels, of type array. 66}, 67});
show all 67 lines
1pubnub.addListener(newStatusListener(){ 2// PubNub status 3@Override 4publicvoidstatus(PubNub pubnub,PNStatus status){ 5switch(status.getCategory()){ 6/* handle various statuses */ 7} 8} 9}); 10 11pubnub.addListener(newEventListener(){ 12// Messages 13@Override 14publicvoidmessage(PubNub pubnub,PNMessageResult message){ 15String messagePublisher = message.getPublisher(); 16System.out.println("Message publisher: "+ messagePublisher); 17System.out.println("Message Payload: "+ message.getMessage()); 18System.out.println("Message Subscription: "+ message.getSubscription()); 19System.out.println("Message Channel: "+ message.getChannel()); 20System.out.println("Message timetoken: "+ message.getTimetoken()); 21} 22 23// Presence 24@Override 25publicvoidpresence(@NotNullPubNub pubnub,@NotNullPNPresenceEventResult presence){ 26System.out.println("Presence Event: "+ presence.getEvent()); 27// Can be join, leave, state-change or timeout 28 29System.out.println("Presence Channel: "+ presence.getChannel()); 30// The channel to which the message was published 31 32System.out.println("Presence Occupancy: "+ presence.getOccupancy()); 33// Number of users subscribed to the channel 34 35System.out.println("Presence State: "+ presence.getState()); 36// User state 37 38System.out.println("Presence UUID: "+ presence.getUserId()); 39// User ID to which this event is related 40 41 presence.getJoin(); 42// List of users that have joined the channel (if event is 'interval') 43 44 presence.getLeave(); 45// List of users that have left the channel (if event is 'interval') 46 47 presence.getTimeout(); 48// List of users that have timed-out off the channel (if event is 'interval') 49 50 presence.getHereNowRefresh(); 51// Indicates to the client that it should call 'hereNow()' to get the 52// complete list of users present in the channel. 53} 54 55// Signals 56@Override 57publicvoidsignal(PubNub pubnub,PNSignalResult pnSignalResult){ 58System.out.println("Signal publisher: "+ signal.getPublisher()); 59System.out.println("Signal payload: "+ signal.getMessage()); 60System.out.println("Signal subscription: "+ signal.getSubscription()); 61System.out.println("Signal channel: "+ signal.getChannel()); 62System.out.println("Signal timetoken: "+ signal.getTimetoken()); 63} 64 65// Message reaction 66@Override 67publicvoidmessageAction(PubNub pubnub,PNMessageActionResult pnActionResult){ 68PNMessageAction pnMessageAction = pnActionResult.getAction(); 69System.out.println("Message reaction type: "+ pnMessageAction.getType()); 70System.out.println("Message reaction value: "+ pnMessageAction.getValue()); 71System.out.println("Message reaction User ID: "+ pnMessageAction.getUserId()); 72System.out.println("Message reaction actionTimetoken: "+ pnMessageAction.getActionTimetoken()); 73System.out.println("Message reaction messageTimetoken: "+ pnMessageAction.getMessageTimetoken());] 74System.out.println("Message reaction subscription: "+ pnActionResult.getSubscription()); 75System.out.println("Message reaction channel: "+ pnActionResult.getChannel()); 76System.out.println("Message reaction timetoken: "+ pnActionResult.getTimetoken()); 77} 78 79// File Sharing 80@Override 81publicvoidfile(PubNub pubnub,PNFileEventResult pnFileEventResult){ 82System.out.println("File channel: "+ pnFileEventResult.getChannel()); 83System.out.println("File publisher: "+ pnFileEventResult.getPublisher()); 84System.out.println("File message: "+ pnFileEventResult.getMessage()); 85System.out.println("File timetoken: "+ pnFileEventResult.getTimetoken()); 86System.out.println("File file.id: "+ pnFileEventResult.getFile().getId()); 87System.out.println("File file.name: "+ pnFileEventResult.getFile().getName()); 88System.out.println("File file.url: "+ pnFileEventResult.getFile().getUrl()); 89} 90});
1// Listener's class should conform to `PNEventsListener` protocol 2// in order to have access to available callbacks. 3 4// Adding listener. 5[pubnub addListener:self]; 6 7// Callbacks listed below. 8 9-(void)client:(PubNub *)pubnub didReceiveMessage:(PNMessageResult *)message { 10 NSString *channel = message.data.channel;// Channel on which the message has been published 11 NSString *subscription = message.data.subscription;// Wild-card channel or channel on which PubNub client actually subscribed 12 NSNumber *timetoken = message.data.timetoken;// Publish timetoken 13 id msg = message.data.message;// Message payload 14 NSString *publisher = message.data.publisher;// Message publisher 15} 16 17-(void)client:(PubNub *)pubnub didReceiveSignal:(PNSignalResult *)signal { 18 NSString *channel = message.data.channel;// Channel on which the signal has been published 19 NSString *subscription = message.data.subscription;// Wild-card channel or channel on which PubNub client actually subscribed 20 NSNumber *timetoken = message.data.timetoken;// Signal timetoken 21 id msg = message.data.message;// Signal payload 22 NSString *publisher = message.data.publisher;// Signal publisher 23} 24 25-(void)client:(PubNub *)pubnub didReceiveMessageAction:(PNMessageActionResult *)action { 26 NSString *channel = action.data.channel;// Channel on which the message has been published 27 NSString *subscription = action.data.subscription;// Wild-card channel or channel on which PubNub client actually subscribed 28 NSString *event = action.data.event;// Can be: added or removed 29 NSString *type = action.data.action.type;// Message reaction type 30 NSString *value = action.data.action.value;// Message reaction value 31 NSNumber *messageTimetoken = action.data.action.messageTimetoken;// Timetoken of the original message 32 NSNumber *actionTimetoken = action.data.action.actionTimetoken;// Timetoken of the message reaction 33 NSString *uuid = action.data.action.uuid;// UUID of user which added / removed message reaction 34} 35 36-(void)client:(PubNub *)pubnub didReceivePresenceEvent:(PNPresenceEventResult *)event { 37 NSString *channel = message.data.channel;// Channel on which presence changes 38 NSString *subscription = message.data.subscription;// Wild-card channel or channel on which PubNub client actually subscribed 39 NSString *presenceEvent = event.data.presenceEvent;// Can be: join, leave, state-change, timeout or interval 40 NSNumber *occupancy = event.data.presence.occupancy;// Number of users subscribed to the channel (not available for state-change event) 41 NSNumber *timetoken = event.data.presence.timetoken;// Presence change timetoken 42 NSString *uuid = event.data.presence.uuid;// UUID of user for which presence change happened 43 44// Only for 'state-change' event 45 NSDictionary *state = event.data.presence.state;// User state (only for state-change event) 46 47// Only for 'interval' event 48 NSArray<NSString *>*join = event.data.presence.join;// UUID of users which recently joined channel 49 NSArray<NSString *>*leave = event.data.presence.leave;// UUID of users which recently leaved channel 50 NSArray<NSString *>*timeout = event.data.presence.timeout;// UUID of users which recently timed out on channel 51} 52 53-(void)client:(PubNub *)pubnub didReceiveObjectEvent:(PNObjectEventResult *)event { 54 NSString *channel = event.data.channel;// Channel to which the event belongs 55 NSString *subscription = event.data.subscription;// Wild-card channel or channel on which PubNub client actually subscribed 56 NSString *event = event.data.event;// Can be: set or delete 57 NSString *type = event.data.type;// Entity type: channel, uuid or membership 58 NSNumber *timestamp = event.data.timestamp;// Event timestamp 59 60 PNChannelMetadata *channelMetadata = event.data.channelMetadata;// Updated channel metadata (only for channel entity type) 61 PNUUIDMetadata *uuidMetadata = event.data.uuidMetadata;// Updated channel metadata (only for uuid entity type) 62 PNMembership *membership = event.data.membership;// Updated channel metadata (only for membership entity type) 63} 64 65-(void)client:(PubNub *)pubnub didReceiveFileEvent:(PNFileEventResult *)event { 66 NSString *channel = event.data.channel;// Channel to which file has been uploaded 67 NSString *subscription = event.data.subscription;// Wild-card channel or channel on which PubNub client actually subscribed 68 id message = event.data.message;// Message added for uploaded file 69 NSString *publisher = event.data.publisher;// UUID of file uploader 70 NSURL *fileDownloadURL = event.data.file.downloadURL;// URL which can be used to download file 71 NSString *fileIdentifier = event.data.file.identifier;// Unique file identifier 72 NSString *fileName = event.data.file.name;// Name with which file has been stored remotely 73} 74 75-(void)client:(PubNub *)pubnub didReceiveStatus:(PNStatus *)status { 76 PNStatusCategory category = status.category;// One of PNStatusCategory fields to identify status of operation processing 77 BOOL isError = status.isError;// Whether any kind of error happened. 78 NSInteger statusCode = status.statusCode;// Related request processing status code 79 BOOL isTLSEnabled = status.isTLSEnabled;// Whether secured connection enabled 80 NSString *uuid = status.uuid;// UUID which configured for passed client 81 NSString *authKey = status.authKey;// Auth token configured for passed client 82 NSString *origin = status.origin;// Origin against which request has been sent 83 NSURLRequest *clientRequest = status.clientRequest;// Request which has been used to send last request (may be nil) 84 BOOL willAutomaticallyRetry = status.willAutomaticallyRetry;// Whether client will try to perform automatic retry 85 86// Following is available when operation == PNSubscribeOperation, 87// because status is PNSubscribeStatus instance in this case 88 PNSubscribeStatus *subscribeStatus =(PNSubscribeStatus *)status; 89 NSNumber *currentTimetoken = subscribeStatus.currentTimetoken;// Timetoken which has been used for current subscribe request 90 NSNumber *lastTimeToken = subscribeStatus.lastTimeToken;// Timetoken which has been used for previous subscribe request 91 NSArray<NSString *>*subscribedChannels = subscribeStatus.subscribedChannels;// List of channels on which client currently subscribed 92 NSArray<NSString *>*subscribedChannelGroups = subscribeStatus.subscribedChannelGroups;// List of channel groups on which client currently subscribed 93 NSString *channel = subscribeStatus.data.channel;// Name of channel to which status has been received 94 NSString *subscription = subscribeStatus.data.subscription;// Wild-card channel or channel on which PubNub client actually subscribed 95 NSNumber *timetoken = subscribeStatus.data.timetoken;// Timetoken at which event arrived 96 NSDictionary *userMetadata = subscribeStatus.data.userMetadata;// Metadata / envelope which has been passed along with event 97 98// Following is available when isError == YES, 99// because status is PNErrorStatus instance in this case 100 PNErrorStatus *errorStatus =(PNErrorStatus *)status; 101 id associatedObject = errorStatus.associatedObject;// Data which may contain related information (not decrypted message for example) 102 NSArray<NSString *>*erroredChannels = errorStatus.errorData.channels;// List of channels for which error reported (mostly because of Access Manager) 103 NSArray<NSString *>*erroredChannelGroups = errorStatus.errorData.channelGroups;// List of channel groups for which error reported (mostly because of Access Manager) 104 NSString *errorInformation = errorStatus.errorData.information;// Stringified information about error 105 id errorData = errorStatus.errorData.data;// Additional error information from PubNub service 106}