User Presence

User presence allows you to show when a user was last active and if they are online right now. Whenever you read a user the data will look like this:

guard let member = channelController.channel?.lastActiveMembers.first else { return }
let isOnline = member.isOnline
let lastActiveAt = member.lastActiveAt

The online field indicates if the user is online. The status field stores text indicating the current user status.

The last_active field is updated when a user connects and then refreshed every 15 minutes.

Invisible

To mark your user as invisible, you can update your user to set the invisible property to true. Your user will remain invisible even if you disconnect and reconnect. You must explicitly set invisible to false in order to become visible again.

// become invisible
await client.upsertUser({
  id: "unique_user_id",
  invisible: true,
});

// become visible
await client.upsertUser({
  id: "unique_user_id",
  invisible: false,
});

You can also set your user to invisible when connecting by setting the invisible property to true. You can also set a custom status message at the same time:

chatClient.connectUser(
  userInfo: .init(
    id: userID,
    isInvisible: true
  ),
  token: token
) { error in
  // …
}

When invisibleis set to true, the current user will appear as offline to other users.

Listening to Presence Changes

Of course, you want to listen to the user presence changes. This allows you to show a user as offline when they leave and update their status in real time. These 3 endpoints allow you to watch user presence:

class PresenceObservingChannelVC: ChatChannelVC, EventsControllerDelegate {
  let eventsController: EventsController!

  override func viewDidLoad() {
    super.viewDidLoad()

    eventsController.delegate = self
  }

  func eventsController(_ controller: EventsController, didReceiveEvent event: Event) {
    if let event = event as? UserPresenceChangedEvent {
      showUser(event.user, isOnline: event.user.isOnline)
    }
  }
}

A users online status change can be handled via event delegation by subscribing to the user.presence.changed event the same you do for any other event.

© Getstream.io, Inc. All Rights Reserved.