SwiftSwift Native Presence API Reference for Realtime Apps

 
These docs are for the new PubNub Swift SDK written purely in Swift. To view the docs for the Older version (the PubNub Objective-C SDK wrapper for Swift), have a look here.

Presence enables you to track the online and offline status of users and devices in realtime, 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:

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 hereNow() function in your application.
To call Here Now you can use the following method(s) in the Swift SDK:
  1. ParameterTypeRequiredDefaultDescription
    onArrayYesThe 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
    andArrayOptional[] Empty ArrayThe list of channel groups for which will return occupancy results from.
    includeUUIDsBoolOptionaltrueSetting uuid to false disables the return of uuids.
    alsoBoolOptionalfalseSetting this flag to true will return the subscribe state information as well.
pubnub.hereNow(on: ["my_channel"]) { result in
  switch result {
  case let .success(response):
    print("Successful hereNow Response: \(response)")
  case let .failure(error):
    print("Failed hereNow Response: \(error.localizedDescription)")
  }
})
Response objects returned by the client in response to a call to the Here Now API on the channel:
public struct HereNowPayload: Codable {
  public let totalOccupancy: Int
  public let totalChannels: Int
  public let channels: [String: HereNowChannelsPayload]
  public let uuids: [String]
}

public struct HereNowChannelsPayload: Codable {
  public let occupancy: Int
  public let uuids: [HereNowUUIDPayload]
}

public struct HereNowUUIDPayload: Codable {
  public let uuid: String
  public let state: [String: AnyJSON]?
}
  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.
    pubnub.hereNow(
      on: ["my-channel"],
      also: true
    ) { result in
      switch result {
      case let .success(response):
        print("Successful hereNow Response: \(response)")
      case let .failure(error):
        print("Failed hereNow Response: \(error.localizedDescription)")
      }
    }
    HereNowPayload(
      channels: 
        ["my-channel": HereNowChannelsPayload(
          occupancy: 5, 
          uuids: [
            HereNowUUIDPayload(uuid: "myUUID0", state: nil), 
            HereNowUUIDPayload(uuid: "myUUID1", state: Optional(["age": 15])), 
            HereNowUUIDPayload(uuid: "b9eb408c-bcec-4d34-b4c4-fabec057ad0d", state: nil), 
            HereNowUUIDPayload(uuid: "myUUID2", state: Optional(["age": 15])), 
            HereNowUUIDPayload(uuid: "myUUID9", state: Optional([["age": 24]))
          ]
        )
      ], 
      totalOccupancy: 5, 
      totalChannels: 1
    )
  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:
    pubnub.hereNow(
      on: ["my-channel"],
      includeUUIDs: false
    ) { result in
      switch result {
      case let .success(response):
        print("Successful hereNow Response: \(response)")
      case let .failure(error):
        print("Failed hereNow Response: \(error.localizedDescription)")
      }
    }
    HereNowPayload(
      channels: [
        "my-channel": HereNowChannelsPayload(
          occupancy: 1, 
          uuids: [])
      ], 
      totalOccupancy: 1, 
      totalChannels: 1
    )
  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:
    pubnub.hereNow(
      on: [],
      also: true
    ) { result in
      switch result {
      case let .success(response):
        print("Successful hereNow Response: \(response)")
      case let .failure(error):
        print("Failed hereNow Response: \(error.localizedDescription)")
      }
    }
    HereNowPayload(
      channels: [
        "lobby": HereNowChannelsPayload(
          occupancy: 1, 
          uuids: [
            HereNowUUIDPayload(uuid: "dara01", state: Optional(["age": 10]))
          ]), 
        "game01": HereNowChannelsPayload(
          occupancy: 2, 
          uuids: [
            HereNowUUIDPayload(uuid: "jason01", state: Optional(["age": 15])),
            HereNowUUIDPayload(uuid: "jason01", state: nil)
          ]), 
      ], 
      totalOccupancy: 3, 
      totalChannels: 2
    )
  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
    pubnub.hereNow(
      on: []
    ) { result in
      switch result {
      case let .success(response):
        print("Successful hereNow Response: \(response)")
      case let .failure(error):
        print("Failed hereNow Response: \(error.localizedDescription)")
      }
    }
    HereNowPayload(
      channels: [
        "lobby": HereNowChannelsPayload(
          occupancy: 1, 
          uuids: [
            HereNowUUIDPayload(uuid: "dara01", state: nil)
          ]), 
        "game01": HereNowChannelsPayload(
          occupancy: 2, 
          uuids: [
            HereNowUUIDPayload(uuid: "jason01", state: nil),
            HereNowUUIDPayload(uuid: "jason01", state: nil)
          ]), 
      ], 
      totalOccupancy: 3, 
      totalChannels: 2
    )
  5. 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.
    pubnub.hereNow(
      on: [],
      and: ["my-channel-group"]
    ) { result in
      switch result {
      case let .success(response):
        print("Successful hereNow Response: \(response)")
      case let .failure(error):
        print("Failed hereNow Response: \(error.localizedDescription)")
      }
    }
    HereNowPayload(
      channels: [
        "ch1": HereNowChannelsPayload(
          occupancy: 1, 
          uuids: [
            HereNowUUIDPayload(uuid: "user1", state: nil)
          ]), 
        "ch2": HereNowChannelsPayload(
          occupancy: 1, 
          uuids: [
            HereNowUUIDPayload(uuid: "user1", state: nil)
          ]), 
      ], 
      totalOccupancy: 2, 
      totalChannels: 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 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. ParameterTypeRequiredDescription
    forStringYesSpecifies the uuid to return channel list for.
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: "db9c5e39-7c95-40f5-8d71-125765b6f561") { result in
  switch result {
  case let .success(response):
    print("Successful WhereNow Response: \(response)")
  case let .failure(error):
    print("Failed WhereNow Response: \(error.localizedDescription)")
  }
}
Response object returned by the client when the Where Now API is called:
public struct WhereNowPayload: Codable {
  public let channels: [String]
}

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. ParameterTypeRequiredDefaultsDescription
    state[String: JSONCodableScalar]YesThe state Dictionary to store. Nesting of Dictionary values is not 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.
  1. ParameterTypeRequiredDefaultsDescription
    forStringYesThe 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[] The list of channel groups to get the state on.
pubnub.setPresence(
  state: ["New": "State"],
  on: ["channelSwift"],
  and: ["demo"]
) { result in
  switch result {
  case let .success(response):
    print("Successful Set State Response: \(response)")
  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(response):
    print("Successful Get State Response: \(response)")
  case let .failure(error):
    print("Failed Get State Response: \(error.localizedDescription)")
  }
}

// [Channel Name : State]
[String: [String: AnyJSON]]