Presence API for PubNub Swift Native SDK
Note
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, as well as 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 Requires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-
Description
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.
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)?)
Parameter Type Required Defaults Description on
[String] Yes The list of channels
to return occupancy results from.and
[String] Optional []
The list of channel groups
for which will return occupancy results from.includeUUIDs
Bool Optional true
Setting uuid
tofalse
disables the return of UUIDs.includeState
Bool Optional false
Setting this flag to true
will return the subscribe state information as well.custom
RequestConfiguration Optional RequestConfiguration()
An object that allows for per-request customization of PubNub Configuration or Network Session completion
((Result<[String: PubNubPresence], Error>) -> Void)? Optional nil
The async Result
of the method callCompletion Handler Result
Success A
Dictionary
of channels mapped to their respectivePubNubPresence
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-onRequires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-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 settingUUIDs
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 Requires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-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 Requires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-
Description
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.
Note
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)?)
Parameter Type Required Defaults Description for
String Yes Specifies the UUID
to return channel list for.custom
RequestConfiguration Optional RequestConfiguration()
An object that allows for per-request customization of PubNub Configuration or Network Session completion
((Result<[String: [String]], Error>) -> Void)? Optional nil
The async Result
of the method callCompletion Handler Result
- Success A
Dictionary
of UUIDs mapped to their respectiveArray
of channels they have presence on - Failure An
Error
describing the failure
- Success A
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 Requires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-
Description
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)
setPresence( state: [String: JSONCodableScalar], on channels: [String], and groups: [String] = [], custom requestConfig: RequestConfiguration = RequestConfiguration(), completion: ((Result<JSONCodable, Error>) -> Void)?)
Parameter Type Required Defaults Description state
[String: JSONCodableScalar] Yes The state
Dictionary to store. Nesting of Dictionary values isn't permitted, and key names beginning with prefixpn
are reserved. Setting thestate
will overwrite the previous values set. Clearing out thestate
involves passing in an empty Dictionaryon
[String] No The list of channel to set the state on. Pass an empty array to not set. and
[String] No The list of channel groups to set the state on. custom
RequestConfiguration Optional RequestConfiguration()
An object that allows for per-request customization of PubNub Configuration or Network Session completion
((Result<JSONCodable, Error>) -> Void)? Optional nil
The async Result
of the method callCompletion Handler Result
- Success The presence State set as a
JSONCodable
- Failure An
Error
describing the failure
- Success The presence State set as a
getPresenceState( for uuid: String, on channels: [String], and groups: [String], custom requestConfig: RequestConfiguration = RequestConfiguration(), completion: ((Result<(uuid: String, stateByChannel: [String: JSONCodable]), Error>) -> Void)?)
Parameter Type Required Defaults Description for
String Yes The UUID to retrieve the state for. on
[String] No The list of channel to get the state on. Pass an empty array to not get. and
[String] No [] custom
RequestConfiguration Optional RequestConfiguration()
An object that allows for per-request customization of PubNub Configuration or Network Session completion
((Result<(uuid: String, stateByChannel: [String: JSONCodable]), Error>) -> Void)? Optional nil
The async Result
of the method callCompletion Handler Result
- Success A
Tuple
containing the UUID that set the State and aDictionary
of channels mapped to their respective State - Failure An
Error
describing the failure
- Success A
Basic Usage
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)")
}
}
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)") } }