iOSiOSCocoaSwiftiOS Swift Presence API Reference for Realtime Apps

Go to Publish & Subscribe


Requires Presence add-on XRequires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:

http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
You can obtain information about the current state of a channel including a list of unique user-ids currently subscribed to the channel and the total occupancy count of the channel by calling the hereNowForChannel function in your application.
To call Here Now you can use the following method(s) in the Swift SDK:
  1. ParameterTypeRequiredDescription
    channelStringYesChannel name to retrieve the Here Now information.
    closurePNHereNowCompletionBlockYesThe completion closure has two arguments: result - in case of successful request processing (data field will contain results of presence audition operation); status - in case if error occurred during request processing (errorData contains error information).
  2. ParameterTypeRequiredDescription
    channelStringYesChannel name to retrieve the Here Now information.
    levelPNHereNowVerbosityLevelYesPNHereNowVerbosityLevel enum filters the response based on the value selected.
    closurePNHereNowCompletionBlockYesThe completion closure has two arguments: result - in case of successful request processing (data field will contain results of presence audition operation); status - in case if error occurred during request processing (errorData contains error information).
// With .UUID client will pull out list of unique identifiers and occupancy information.
self.client.hereNowForChannel("my_channel", withVerbosity: .UUID,
							  completion: { (result, status) in
										
	if status == nil {
		
		/**
		 Handle downloaded presence information using:
			result.data.uuids - list of uuids.
			result.data.occupancy - total number of active subscribers.
		 */
	}
	else {
		
		/**
		 Handle presence audit error. Check 'category' property to find
		 out possible reason because of which request did fail.
		 Review 'errorData' property (which has PNErrorData data type) of status
		 object to get additional information about issue.
		 
		 Request can be resent using: status.retry()
		 */
	}
})
Response objects which is returned by client when Here Now API for channel used:
open class PNPresenceGlobalHereNowData : PNServiceData {
    
    // Active channels list.
    open var channels: [String : [AnyHashable : Any]] { get }
    // Total number of active channels.
    open var totalChannels: NSNumber { get }
    // Total number of subscribers.
    open var totalOccupancy: NSNumber { get }
}

open class PNPresenceChannelGroupHereNowData : PNPresenceGlobalHereNowData {
    
}

open class PNPresenceChannelGroupHereNowResult : PNResult {
    
    // Stores reference on channel group presence request processing information.
    open var data: PNPresenceChannelGroupHereNowData { get }
}
  1. Requires Presence add-on XRequires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    /**
     With .state client aside from occupancy and unique identifiers will will pull out
     state information associated with them.
     */
    self.client.hereNowForChannel("my_channel", withVerbosity: .state,
    							  completion: { (result, status) in
    										
    	if status == nil {
    		
    		/**
    		 Handle downloaded presence information using:
    		 result.data.uuids - list of uuids. Each uuid entry will have next 
    		 					 fields: "uuid" - identifier and "state" if it 
    		 					 has been provided.
    		 result.data.occupancy - total number of active subscribers.
    		 */
    	}
    	else {
    		
    		/**
    		 Handle presence audit error. Check 'category' property
    		 to find out possible reason because of which request did fail.
    		 Review 'errorData' property (which has PNErrorData data type) of status
    		 object to get additional information about issue.
    		 
    		 Request can be resent using: status.retry()
    		 */
    	}
    })
    {
    	"status" : 200,
    	"message" : "OK",
    	"service" : "Presence",
    	"uuids" : [
    		{
    			"uuid" : "myUUID0"
    		},
    		{
    			"state" : {
    				"abcd" : {
    					"age" : 15
    				}
    			},
    			"uuid" : "myUUID1"
    		},
    		{
    			"uuid" : "b9eb408c-bcec-4d34-b4c4-fabec057ad0d"
    		},
    		{
    			"state" : {
    				"abcd" : {
    					"age" : 15
    				}
    			},
    			"uuid" : "myUUID2"
    		},
    		{
    			"state" : {
    				"abcd" : {
    					"age" : 24
    				}
    			},
    			"uuid" : "myUUID9"
    		}
    	],
    	"occupancy" : 5
    }
  2. Requires Presence add-on XRequires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    You can return only the occupancy information for a single channel by specifying the channel and setting UUIDs to false:
    // With .occupancy client will pull out only occupancy information.
    self.client.hereNowForChannel("my_channel", withVerbosity: .occupancy,
    							  completion: { (result, status) in
    								
    	if status == nil {
    		
    		/**
    		 Handle downloaded presence information using:
    		 	result.data.occupancy - total number of active subscribers.
    		 */
    	}
    	else {
    		
    		/**
    		 Handle presence audit error. Check 'category' property
    		 to find out possible reason because of which request did fail.
    		 Review 'errorData' property (which has PNErrorData data type) of status
    		 object to get additional information about issue.
    		 
    		 Request can be resent using: status.retry()
    		 */
    	}
    })
    {
        "status": 200,
        "message": "OK",
        "payload": {
            "channels": {
                "81d8d989-b95f-443c-a726-04fac323b331": { 
                    "uuids": [ "70fc1140-22b5-4abc-85b2-ff8c17b24d59" ], 
                    "occupancy": 1 
                },
                "81b7a746-d153-49e2-ab70-3037a75cec7e": { 
                    "uuids": [ "91363e7f-584b-49cc-822c-52c2c01e5928" ],
                    "occupancy": 1
                },
                "c068d15e-772a-4bcd-aa27-f920b7a4eaa8": { 
                    "uuids": [ "ccfac1dd-b3a5-4afd-9fd9-db11aeb65395" ],
                    "occupancy": 1
                }
            },
            "total_channels": 3,
            "total_occupancy": 3
        },
        "service": "Presence"
    }
  3. Requires Presence add-on XRequires that the Presence add-on is enabled with Global Here Now checked for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    You can return the list of UUIDs and occupancy for all channels by omitting the channel:
    // With .UUID client will pull out list of unique identifiers and occupancy information.
    self.client.hereNowWithVerbosity(.UUID, completion: { (result, status) in
    	
    	if status == nil {
    		
    		/**
    		 Handle downloaded presence information using:
    		 result.data.channels - dictionary with active channels and presence
    		 						information on each. Each channel will have
    		 						next fields: "uuids" - list of subscribers;
    		 						"occupancy" - number of active subscribers.
    		 result.data.totalChannels - total number of active channels.
    		 result.data.totalOccupancy - total number of active subscribers.
    		 */
    	}
    	else {
    		
    		/**
    		 Handle presence audit error. Check 'category' property
    		 to find out possible reason because of which request did fail.
    		 Review 'errorData' property (which has PNErrorData data type) of status
    		 object to get additional information about issue.
    		 
    		 Request can be resent using: status.retry()
    		 */
    	}
    })
    {
        "total_channels" : 2,
        "total_occupancy" : 3,
        "channels" : {
            "lobby" : {
                "occupancy" : 1,
                "uuids" : [
                    "dara01"
                ]
            },
            "game01" : {
                "occupancy" : 2,
                "uuids" : [
                    "jason01",
                    "jason02"
                ]
            }
        }
    }
  4. Requires Presence add-on XRequires that the Presence add-on is enabled with Global Here Now checked for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    You can return only the occupancy information (Global Here Now) by omitting the channel name
    self.client.hereNowWithCompletion({ (result, status) in
    
    	if status == nil {
    
    		/**
    		 Handle downloaded presence information using:
    			result.data.channels - dictionary with active channels and presence
    								   information on each. Each channel will have
    								   next fields: "uuids" - list of subscribers;
    								   "occupancy" - number of active subscribers.
    								   Each uuids entry has next fields:
    								   "uuid" - identifier and "state" if it has been
    								   provided.
    			result.data.totalChannels - total number of active channels.
    			result.data.totalOccupancy - total number of active subscribers.
    		 */
    	}
    	else {
    
    		/**
    		 Handle presence audit error. Check 'category' property
    		 to find out possible reason because of which request did fail.
    		 Review 'errorData' property (which has PNErrorData data type) of status
    		 object to get additional information about issue.
    
    		 Request can be resent using: status.retry()
    		 */
    	}
    })
    {
        "status": 200,
        "message": "OK",
        "payload": {
            "channels": {
                "81d8d989-b95f-443c-a726-04fac323b331": { 
                    "uuids": [ "70fc1140-22b5-4abc-85b2-ff8c17b24d59" ], 
                    "occupancy": 1 
                },
                "81b7a746-d153-49e2-ab70-3037a75cec7e": { 
                    "uuids": [ "91363e7f-584b-49cc-822c-52c2c01e5928" ],
                    "occupancy": 1
                },
                "c068d15e-772a-4bcd-aa27-f920b7a4eaa8": { 
                    "uuids": [ "ccfac1dd-b3a5-4afd-9fd9-db11aeb65395" ],
                    "occupancy": 1
                }
            },
            "total_channels": 3,
            "total_occupancy": 3
        },
        "service": "Presence"
    }
Request information about subscribers on specific channel group. This API method will retrieve the list of UUIDs along with their state for each remote data object and the number of subscribers.
To do Here Now for Channel Groups you can use the following method(s) in the Swift SDK
  1. ParameterTypeRequiredDescription
    groupStringYesChannel Group name to retrieve the Here Now information.
    closurePNChannelGroupHereNowCompletionBlockYesThe completion closure has two arguments: result - in case of successful request processing (data field will contain results of presence audition operation); status - in case if error occurred during request processing (errorData contains error information).
  2. ParameterTypeRequiredDescription
    group
    String
    Yes
    Channel Group name to retrieve the Here Now information.
    level
    PNHereNowVerbosityLevel
    Yes
    PNHereNowVerbosityLevel enum filters the response based on the value selected.
    closure
    PNChannelGroupHereNowCompletionBlock
    Yes
    The completion closure has two arguments: result - in case of successful request processing (data field will contain results of presence audition operation); status - in case if error occurred during request processing (errorData contains error information).
self.client.hereNowForChannelGroup("my_group", withCompletion: { (result, status) in

	if status == nil {

		/**
		 Handle downloaded presence information using:
			result.data.channels - dictionary with active channels and presence information on 
								   each. Each channel will have next fields: "uuids" - list of
								   subscribers; occupancy - number of active subscribers.
								   Each uuids entry has next fields: "uuid" - identifier and 
								   "state" if it has been provided.
			result.data.totalChannels - total number of active channels.
			result.data.totalOccupancy - total number of active subscribers.
		 */
	}
	else {

		/**
		 Handle presence audit error. Check 'category' property
		 to find out possible reason because of which request did fail.
		 Review 'errorData' property (which has PNErrorData data type) of status
		 object to get additional information about issue.

		 Request can be resent using: status.retry()
		 */
	}
})
Response objects which is returned by client when Here Now API for channel group used:
open class PNPresenceGlobalHereNowData : PNServiceData {
    
    // Active channels list.
    open var channels: [String : [AnyHashable : Any]] { get }
    // Total number of active channels.
    open var totalChannels: NSNumber { get }
    // Total number of subscribers.
    open var totalOccupancy: NSNumber { get }
}

open class PNPresenceChannelGroupHereNowData : PNPresenceGlobalHereNowData {
    
}

open class PNPresenceChannelGroupHereNowResult : PNResult {
    
    // Stores reference on channel group presence request processing information.
    open var data: PNPresenceChannelGroupHereNowData { get }
}
Return Occupancy for all channels by calling the hereNowWithCompletion function in your application.
To call Global Here Now you can use the following method(s) in the Swift SDK:
  1. ParameterTypeRequiredDescription
    closurePNGlobalHereNowCompletionBlockYesThe completion closure has two arguments: result - in case of successful request processing (data field will contain results of presence audition operation); status - in case if error occurred during request processing (errorData contains error information).
  2. ParameterTypeRequiredDescription
    levelPNHereNowVerbosityLevelYesPNHereNowVerbosityLevel enum filters the response based on the value selected.
    closurePNGlobalHereNowCompletionBlockYesThe completion closure has two arguments: result - in case of successful request processing (data field will contain results of presence audition operation); status - in case if error occurred during request processing (errorData contains error information).
self.client.hereNowWithCompletion({ (result, status) in

	if status == nil {

		/**
		 Handle downloaded presence information using:
			result.data.channels - dictionary with active channels and presence
								   information on each. Each channel will have
								   next fields: "uuids" - list of subscribers;
								   "occupancy" - number of active subscribers.
								   Each uuids entry has next fields:
								   "uuid" - identifier and "state" if it has been
								   provided.
			result.data.totalChannels - total number of active channels.
			result.data.totalOccupancy - total number of active subscribers.
		 */
	}
	else {

		/**
		 Handle presence audit error. Check 'category' property
		 to find out possible reason because of which request did fail.
		 Review 'errorData' property (which has PNErrorData data type) of status
		 object to get additional information about issue.

		 Request can be resent using: status.retry()
		 */
	}
})
Response objects which is returned by client when Gllobal Here Now API is used:
open class PNPresenceGlobalHereNowResult : PNResult {
    
    // Stores reference on global presence request processing information.
    open var data: PNPresenceGlobalHereNowData { get }
}
Requires Presence add-on XRequires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:

http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
You can obtain information about the current list of channels to which a UUID is subscribed to by calling the whereNowUUID function in your application.
 
If the app is killed/crashes and restarted (or the page containing the PubNub instance is refreshed on the browser) within the heartbeat window no timeout event is generated.
To call whereNowUUID you can use the following method(s) in the Swift SDK:
  1. ParameterTypeRequiredDescription
    uuidStringYesThe UUID for which request should be performed.
    closurePNWhereNowCompletionBlockYesThe completion closure which will be called when the processing is complete, has two arguments: result - in case of successful processing (data will contain results of presence operation); status - in case of error while processing (errorDatacontains error information).
You simply need to define the uuid and the callback function to be used to send the data to as in the example below.
self.client.whereNowUUID(self.client.uuid(), withCompletion: { (result, status) in
			
	if status == nil {
		
		// Handle downloaded presence 'where now' information using: result.data.channels
	}
	else {
		
		/**
		 Handle presence audit error. Check 'category' property
		 to find out possible reason because of which request did fail.
		 Review 'errorData' property (which has PNErrorData data type) of status
		 object to get additional information about issue.
		 
		 Request can be resent using: status.retry()
		 */
	}
})
Response objects which is returned by client when Where Now API is used:
open class PNPresenceWhereNowData : PNServiceData {
    
    // List of channels on which client subscribed.
    open var channels: [String] { get }
}

open class PNPresenceWhereNowResult : PNResult {
    
    // Stores reference on client presence request processing information.
    open var data: PNPresenceWhereNowData { get }
}
Requires Presence add-on XRequires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:

http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
The state API is used to set/get key/value pairs specific to a subscriber uuid.
State information is supplied as a JSON object of key/value pairs.
  1. ParameterTypeRequiredDescription
    state[String : Any]NoReference on dictionary which should be bound to uuid on specified channel. If value is nil, state will be removed for uuid on channel.
    uuidStringYesThe unique user identifier for which state should be bound.
    channelStringYesChannel name against which the store state information is stored.
    closurePNChannelStateCompletionBlockNoThe completion closure which will be called when the processing is complete, has one argument: request processing status - in case of error while processing (errorDatacontains error information).
  2. ParameterTypeRequiredDescription
    state[String : Any]NoReference on dictionary which should be bound to uuid on specified channel group. If value is nil, state will be removed for uuid on group.
    uuidStringYesThe unique user identifier for which state should be bound.
    groupString!YesChannel Group name against which the store state information is stored.
    closurePNChannelStateCompletionBlockNoThe completion closure which will be called when the processing is complete, has one argument: request processing status - in case of error while processing (errorDatacontains error information).
  1. ParameterTypeRequiredDescription
    uuidStringYesThe unique user identifier for which state should be retrieved.
    channelStringYesChannel name to retrieve the state information.
    closurePNChannelStateCompletionBlockYesThe completion closure which will be called when the processing is complete, has two arguments: result - in case of successful processing (data will contain results of client state retrieve operation); status - in case of error while processing (errorDatacontains error information).
  2. ParameterTypeRequiredDescription
    uuidStringYesThe unique user identifier for which state should be retrieved.
    groupStringYesChannel Group name to retrieve the state information.
    closurePNChannelGroupStateCompletionBlockYesThe completion closure which will be called when the processing is complete, has two arguments: result - in case of successful processing (data will contain results of client state retrieve operation); status - in case of error while processing (errorDatacontains error information).
self.client.setState(["Key": "Value"], forUUID: self.client.uuid(), onChannel: "my_channel",
					 withCompletion: { (status) in
								
	if !status.isError {
		
		// Client state successfully modified on specified channel.
	}
	else {
		
		/**
		 Handle client state modification error. Check 'category' property
		 to find out possible reason because of which request did fail.
		 Review 'errorData' property (which has PNErrorData data type) of status
		 object to get additional information about issue.
		 
		 Request can be resent using: status.retry()
		 */
	}
})
self.client.stateForUUID(self.client.uuid(), onChannel: "chat",
						 withCompletion: { (result, status) in
									
	if status == nil {
		
		// Handle downloaded state information using: result.data.state
	}
	else{
		
		/**
		 Handle client state audit error. Check 'category' property
		 to find out possible reason because of which request did fail.
		 Review 'errorData' property (which has PNErrorData data type) of status
		 object to get additional information about issue.
		 
		 Request can be resent using: status.retry()
		 */
	}
})
Response objects which is returned by client when Set State API for channels used:
open class PNClientStateUpdateData : PNChannelClientStateData {

}

open class PNClientStateUpdateStatus : PNErrorStatus {
    
    // Stores reference on client state for channel request processing information.
    open var data: PNClientStateUpdateData { get }
}
Response objects which is returned by client when Get State API for channel used:
open class PNChannelClientStateData : PNServiceData {
    
    // User-provided client state information.
    open var state: [String : Any] { get }
}

open class PNChannelClientStateResult : PNResult {
    
    // Stores reference on client state for channel request processing information.
    open var data: PNChannelClientStateData { get }
}
Response objects which is returned by client when Get State API for channel group used:
open class PNChannelGroupClientStateData : PNServiceData {
    
    // Multi channel client state information.
    open var channels: [String : [AnyHashable : Any]] { get }
}

open class PNChannelGroupClientStateResult : PNResult {
    
    // Stores reference on client state for channel group request processing information.
    open var data: PNChannelGroupClientStateData { get }
}
Requires Presence add-on XRequires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:

http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
The state API is used to set/get key/value pairs specific to a subscriber uuid.
State information is supplied as a JSON object of key/value pairs.
  1. ParameterTypeRequiredDescription
    uuidStringNoUnique user identifier for which state should be bound. Current PubNub user id will be used by default if not set or set to nil.
    state[String: Any]NoData which should be bound to specified uuid on channels / channelGroups.
    channels[String]NoList of the channel names which will store provided state information for uuid. Not required if channelGroups is set.
    channelGroups[String]NoList of channel group names which will store provided state information for uuid. Not required if channels is set.
    completionPNSetStateCompletionBlockNoState modification for user on channel / channel group completion closure which pass only one argument - request status reports state change was successful or not (errorData contains error information in case of failure).
     

    This method uses the builder pattern, you can remove the arguments which are optional.

  1. ParameterTypeRequiredDescription
    uuidStringNoUnique user identifier for which state should be retrieved. Current PubNub user id will be used by default if not set or set to nil.
    channels[String]NoList of the channel names from which state information for uuid will be pulled out. Not required if channelGroups is set.
    channelGroups[String]NoList of channel group names from which state information for uuid will be pulled out. Not required if channels is set.
    completionPNGetStateCompletionBlockYesState audition for user on channel / channel group completion closure which pass two arguments: result - in case of successful request processing data field will contain results of client state retrieve operation; status - in case of error occurred during request processing.
     

    This method uses the builder pattern, you can remove the arguments which are optional.

self.client.state().set().state(["state": "test"])
    .channels(["channel1", "channel12"])
    .channelGroups(["group1", "group2"])
    .performWithCompletion({ (status) in
  
        if !status.isError {
            // Client state successfully modified on specified channels and groups.
        } else {
            /**
             Handle client state modification error. Check 'category' property
             to find out possible reason because of which request did fail.
             Review 'errorData' property (which has PNErrorData data type) of status
             object to get additional information about issue.
 
             Request can be resent using: status.retry()
            */
        }
    });
self.client.state().audit().uuid("PubNub")
    .channels(["channel1", "channel12"])
    .channelGroups(["group1", "group2"])
    .performWithCompletion({ (result, status) in
  
        if status == nil {
            // Handle downloaded state information using: result.data.channels
        } else {
            /**
             Handle client state audit error. Check 'category' property
             to find out possible reason because of which request did fail.
             Review 'errorData' property (which has PNErrorData data type) of status
             object to get additional information about issue.
 
             Request can be resent using: status.retry()
            */
        }
    });

Go to Channel Groups