Presence API for PubNub Swift Native SDK

Migration guide

The PubNub Swift 3.0 SDK contains many significant changes from the 2.x SDK, including breaking changes. Please refer to the PubNub Swift 3.0 Migration Guide for more details.

Presence enables you to track the online and offline status of users and devices in real time, and store custom state information. Presence provides authoritative information on:

  • When a user has joined or left a channel
  • Who, and how many, users are subscribed to a particular channel
  • Which channel(s) an individual user is subscribed to
  • Associated state information for these users

Learn more about our Presence feature here.

Here Now

Requires Presence add-on

This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your 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 hereNow() function in your application.

Cache

This method has a 3 second response cache time.

Method(s)

To call Here Now you can use the following method(s) in the Swift SDK:

hereNow(
on channels: [String],
and groups: [String] = [],
includeUUIDs: Bool = true,
includeState: Bool = false,
custom requestConfig: RequestConfiguration = RequestConfiguration(),
completion: ((Result<[String: PubNubPresence], Error>) -> Void)?
)
ParameterTypeRequiredDefaultDescription
on[String]YesThe list of channels to return occupancy results from.
and[String]Optional[]The list of channel groups for which will return occupancy results from.
includeUUIDsBoolOptionaltrueSetting uuid to false disables the return of UUIDs.
includeStateBoolOptionalfalseSetting this flag to true will return the subscribe state information as well.
customRequestConfigurationOptionalRequestConfiguration()An object that allows for per-request customization of PubNub Configuration or Network Session
completion((Result<[String: PubNubPresence], Error>) -> Void)?OptionalnilThe async Result of the method call

Completion Handler Result

Success

A Dictionary of channels mapped to their respective PubNubPresence

public protocol PubNubPresence {
/// The channel identifier
var channel: String { get }

/// The total number of UUIDs present on the channel
var occupancy: Int { get set }

/// The known UUIDs present on the channel
///
/// The `count` of this Array may differ from the `occupancy` field
var occupants: [String] { get set }

/// The Dictionary of UUIDs mapped to their respective presence state data
var occupantsState: [String: JSONCodable] { get set }
}
Failure

An Error describing the failure.

Basic Usage

Get a list of UUIDs subscribed to channel

pubnub.hereNow(on: ["my_channel"]) { result in
switch result {
case let .success(presenceByChannel):
print("Total channels \(presenceByChannel.totalChannels)")
print("Total occupancy across all channels \(presenceByChannel.totalOccupancy)")
if let myChannelPresence = presenceByChannel["my_channel"] {
print("The occupancy for `my_channel` is \(myChannelPresence.occupancy)")
print("The list of occupants for `my_channel` are \(myChannelPresence.occupants)")
}
case let .failure(error):
print("Failed hereNow Response: \(error.localizedDescription)")
}
})

Other Examples

Return Occupancy Only

Requires Presence add-on

This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

You can return only the occupancy information for a single channel by specifying the channel and setting UUIDs to false:

pubnub.hereNow(
on: ["my-channel"],
includeUUIDs: false
) { result in
switch result {
case let .success(presenceByChannel):
if let myChannelPresence = presenceByChannel["my_channel"] {
print("The occupancy for `my_channel` is \(myChannelPresence.occupancy)")
}
case let .failure(error):
print("Failed hereNow Response: \(error.localizedDescription)")
}
}

Channel Group Usage

Requires Presence add-on

This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

pubnub.hereNow(
on: [],
and: ["my-channel-group"]
) { result in
switch result {
case let .success(presenceByChannel):
print("The `Dictionary` of channels mapped to their respective `PubNubPresence`: \(presenceByChannel)")
case let .failure(error):
print("Failed hereNow Response: \(error.localizedDescription)")
}
}

Where Now

Requires Presence add-on

This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

You can obtain information about the current list of channels to which a UUID is subscribed to by calling the whereNow() function in your application.

Timeout events

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.

Method(s)

To call whereNow() you can use the following method(s) in the Swift SDK:

whereNow(
for uuid: String,
custom requestConfig: RequestConfiguration = RequestConfiguration(),
completion: `((Result<[String: [String]], Error>) -> Void)?`
)
ParameterTypeRequiredDefaultDescription
forStringYesSpecifies the UUID to return channel list for.
customRequestConfigurationOptionalRequestConfiguration()An object that allows for per-request customization of PubNub Configuration or Network Session
completion((Result<[String: [String]], Error>) -> Void)?OptionalnilThe async Result of the method call

Completion Handler Result

Success

A Dictionary of UUIDs mapped to their respective Array of channels they have presence on.

Failure

An Error describing the failure.

Basic Usage

You simply need to define the uuid and the callback function to be used to send the data to as in the example below.

Get a list of channels a UUID is subscribed to

pubnub.whereNow(for: "my-unique-uuid") { result in
switch result {
case let .success(channelsByUUID):
print("A `Dictionary` of UUIDs mapped to their respective `Array` of channels they have presence on \(channelsByUUID)")
if let channels = channelsByUUID["my-unique-uuid"] {
print("The list of channel identifiers for the UUID `my-unique-uuid`: \(channels)")
}
case let .failure(error):
print("Failed WhereNow Response: \(error.localizedDescription)")
}
}

User State

Requires Presence add-on

This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your 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.

Method(s)

Set State

setPresence(
state: [String: JSONCodableScalar],
on channels: [String],
and groups: [String] = [],
custom requestConfig: RequestConfiguration = RequestConfiguration(),
completion: ((Result<JSONCodable, Error>) -> Void)?
)
ParameterTypeRequiredDefaultDescription
state[String: JSONCodableScalar]YesThe state Dictionary to store. Nesting of Dictionary values isn't permitted, and key names beginning with prefix pn are reserved. Setting the state will overwrite the previous values set. Clearing out the state involves passing in an empty Dictionary
on[String]NoThe list of channel to set the state on. Pass an empty array to not set.
and[String]NoThe list of channel groups to set the state on.
customRequestConfigurationOptionalRequestConfiguration()An object that allows for per-request customization of PubNub Configuration or Network Session
completion((Result<JSONCodable, Error>) -> Void)?OptionalnilThe async Result of the method call

Completion Handler Result

Success

The presence State set as a JSONCodable.

Failure

An Error describing the failure.

Get State

getPresenceState(
for uuid: String,
on channels: [String],
and groups: [String],
custom requestConfig: RequestConfiguration = RequestConfiguration(),
completion: ((Result<(uuid: String, stateByChannel: [String: JSONCodable]), Error>) -> Void)?
)
ParameterTypeRequiredDefaultDescription
forStringYesThe UUID to retrieve the state for.
on[String]NoThe list of channel to get the state on. Pass an empty array to not get.
and[String]No[]
customRequestConfigurationOptionalRequestConfiguration()An object that allows for per-request customization of PubNub Configuration or Network Session
completion((Result<(uuid: String, stateByChannel: [String: JSONCodable]), Error>) -> Void)?OptionalnilThe async Result of the method call

Completion Handler Result

Success

A Tuple containing the UUID that set the State and a Dictionary of channels mapped to their respective State.

Failure

An Error describing the failure.

Basic Usage

Set State

pubnub.setPresence(
state: ["new": "state"],
on: ["channelSwift"],
and: ["demo"]
) { result in
switch result {
case let .success(presenceSet):
print("The presence State set as a `JSONCodable`: \(presenceSet)")
case let .failure(error):
print("Failed Set State Response: \(error.localizedDescription)")
}
}

Get State

pubnub.getPresenceState(
for: pubnub.configuration.uuid,
on: ["channelSwift"],
and: ["demo"]
) { result in
switch result {
case let .success(uuid, stateByChannel):
print("The UUID `\(uuid)` has the following presence state \(stateByChannel)")
case let .failure(error):
print("Failed Get State Response: \(error.localizedDescription)")
}
}

Other Examples

Converting the response to a JSON Dictionary

pubnub.setPresence(
state: ["new": "state"],
on: ["channelSwift"]
) { result in
switch result {
case let .success(presenceSet):
print("The String value for `New` is: \(presenceSet.codableValue[rawValue: "New"] as? String)")
case let .failure(error):
print("Failed Set State Response: \(error.localizedDescription)")
}
}

Converting the response to a custom object

struct PresenceState: JSONCodable {
var new: String
}
pubnub.setPresence(
state: ["new": "state"],
on: ["channelSwift"]
) { result in
switch result {
case let .success(presenceSet):
print("The Object representation is: \(try? presenceSet.codableValue.decode(PresenceState.self))")
case let .failure(error):
print("Failed Set State Response: \(error.localizedDescription)")
}
}
Last updated on