SwiftSwift Native Presence API Reference for Realtime Apps

 
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.


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:

https://support.pubnub.com/hc/en-us/articles/360051974791-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 hereNow() function in your application.
To call Here Now you can use the following method(s) in the Swift SDK:
  1. ParameterTypeRequiredDefaultsDescription
    on[String]YesThe list of channels to return occupancy results from. If the list is an empty array, then hereNow() will make a global call to return data for all channels
    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

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)")
  }
})
  1. 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:

    https://support.pubnub.com/hc/en-us/articles/360051974791-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:
      pubnub.hereNow(
        on: ["my-channel"],
        includeState: true
      ) { result in
        switch result {
        case let .success(presenceByChannel):
          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)")
            print("The presence state for uuids present on `my_channel` are \(myChannelPresence.occupantsState)")
          }
        case let .failure(error):
          print("Failed hereNow Response: \(error.localizedDescription)")
        }
      }
  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:

    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 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)")
      }
    }
  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:

    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 (Global Here Now) by omitting the channel name
    pubnub.hereNow(
      on: []
    ) { 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)")
      }
    }
  4. 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:

    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)")
      }
    }

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:

https://support.pubnub.com/hc/en-us/articles/360051974791-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 whereNow() 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 whereNow() you can use the following method(s) in the Swift SDK:
  1. ParameterTypeRequiredDefaultsDescription
    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
You simply need to define the uuid and the callback function to be used to send the data to as in the example below.
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)")
  }
}

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:

https://support.pubnub.com/hc/en-us/articles/360051974791-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. ParameterTypeRequiredDefaultsDescription
    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
  1. ParameterTypeRequiredDefaultsDescription
    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
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)")
  }
}
  1.     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)")
          }
        }
  2.   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)")
        }
      }