Skip to main content
Quick Reference for AI Agents & Developers
  • Subscribe presence: AppSettings.AppSettingsBuilder().subscribePresenceForAllUsers() or .subscribePresenceForFriends() or .subscribePresenceForRoles(_:)
  • Listen for presence: onUserOnline(_:), onUserOffline(_:) in CometChatUserDelegate
  • User status: user.status.online or .offline
  • Last active: user.lastActiveAt — timestamp of last activity
  • Related: Retrieve Users · Connection Status · Users Overview
User Presence helps us understand if a user is available to chat or not.

Real-time Presence

In other words, as a logged-in user, how do I know if a user is online or offline? Based on the settings provided in the AppSettings class while initializing the SDK using the init() method, the logged-in user will receive the presence for the other users in the app. In the AppSettings class, you can set the type of Presence you wish to receive for that particular session of the app.

Presence Subscription

Configure presence subscription during SDK initialization using AppSettings.
// Subscribe to ALL Users
let appSettings = AppSettings.AppSettingsBuilder()
    .subscribePresenceForAllUsers()
    .setRegion(region: "us")
    .build()

CometChat.init(appId: APP_ID, appSettings: appSettings, onSuccess: { success in
    print("CometChat initialized with presence for all users")
}, onError: { error in
    print("Error: \(error.errorDescription)")
})

AppSettingsBuilder Subscription Methods

MethodReturnsDescription
subscribePresenceForAllUsers()AppSettingsBuilderSubscribe to presence updates for all users in the app
subscribePresenceForFriends()AppSettingsBuilderSubscribe to presence updates for friends only
subscribePresenceForRoles(_:)AppSettingsBuilderSubscribe to presence updates for users with specific roles
Builder Configuration:
ParameterTypeDescription
subscribePresenceForAllUsersMethodSubscribes to presence updates for all users in the app. Example: .subscribePresenceForAllUsers()
subscribePresenceForFriendsMethodSubscribes to presence updates for friends only. Example: .subscribePresenceForFriends()
subscribePresenceForRolesMethodSubscribes to presence updates for users with specific roles. Example: .subscribePresenceForRoles(roles: ["admin", "moderator"])
setRegionMethodSets the region for the CometChat app. Example: .setRegion(region: "us")
Subscription Examples:
Use CaseBuilder Configuration
Subscribe to all users.subscribePresenceForAllUsers().setRegion(region: "us").build()
Subscribe to friends only.subscribePresenceForFriends().setRegion(region: "us").build()
Subscribe to specific roles.subscribePresenceForRoles(roles: ["admin", "moderator"]).setRegion(region: "us").build()
  • If none of the subscription methods are used, NO presence updates will be sent
  • Subscription is set per session (app launch)
  • Must be configured BEFORE CometChat.init()

Subscribe to Friends Only

let appSettings = AppSettings.AppSettingsBuilder()
    .subscribePresenceForFriends()
    .setRegion(region: "us")
    .build()

Subscribe to Specific Roles

let appSettings = AppSettings.AppSettingsBuilder()
    .subscribePresenceForRoles(roles: ["admin", "moderator"])
    .setRegion(region: "us")
    .build()

CometChatUserDelegate

Listen for real-time presence updates by conforming to CometChatUserDelegate.
class ViewController: UIViewController, CometChatUserDelegate {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        CometChat.userdelegate = self
    }
    
    // Called when a user comes online
    func onUserOnline(user: User) {
        print("\(user.name ?? "") is now online")
    }
    
    // Called when a user goes offline
    func onUserOffline(user: User) {
        print("\(user.name ?? "") is now offline")
    }
}

Delegate Methods

MethodParameterDescription
onUserOnline(user:)UserCalled when a subscribed user comes online
onUserOffline(user:)UserCalled when a subscribed user goes offline
Event Trigger: Received via CometChatUserDelegate.onUserOnline(user:)User Object Properties:
ParameterTypeDescription
uidString?Unique identifier of the user. Example: "user123"
nameString?Display name of the user. Example: "John Doe"
avatarString?URL to the user’s avatar image. Example: "https://example.com/avatar.png"
linkString?URL to the user’s profile page. Example: nil
roleString?Role assigned to the user. Example: "default"
statusUserStatusCurrent online status of the user. Example: .online
statusMessageString?Custom status message set by the user. Example: nil
lastActiveAtDoubleUnix timestamp of the user’s last activity. Example: 1699900000.0
hasBlockedMeBoolIndicates if this user has blocked the logged-in user. Example: false
blockedByMeBoolIndicates if the logged-in user has blocked this user. Example: false
deactivatedAtDoubleUnix timestamp when user was deactivated (0 if active). Example: 0.0
tags[String]Array of tags associated with the user. Example: []
metadata[String: Any]?Custom metadata dictionary. Example: [:]
Event Trigger: Received via CometChatUserDelegate.onUserOffline(user:)User Object Properties:
ParameterTypeDescription
uidString?Unique identifier of the user. Example: "user123"
nameString?Display name of the user. Example: "John Doe"
avatarString?URL to the user’s avatar image. Example: "https://example.com/avatar.png"
linkString?URL to the user’s profile page. Example: nil
roleString?Role assigned to the user. Example: "default"
statusUserStatusCurrent online status of the user. Example: .offline
statusMessageString?Custom status message set by the user. Example: nil
lastActiveAtDoubleUnix timestamp of the user’s last activity. Example: 1699900300.0
hasBlockedMeBoolIndicates if this user has blocked the logged-in user. Example: false
blockedByMeBoolIndicates if the logged-in user has blocked this user. Example: false
deactivatedAtDoubleUnix timestamp when user was deactivated (0 if active). Example: 0.0
tags[String]Array of tags associated with the user. Example: []
metadata[String: Any]?Custom metadata dictionary. Example: [:]
  • Set delegate in viewDidLoad(): CometChat.userdelegate = self
  • Only receives updates for subscribed users (based on AppSettings)
  • Remove delegate when view is dismissed to avoid memory leaks

Start Listening for Presence

CometChat.userdelegate = self
// This class now conforms to CometChatUserDelegate
// Will receive onUserOnline and onUserOffline callbacks
Setup Configuration:
ParameterTypeDescription
userdelegateCometChatUserDelegateReference to the delegate object. Example: self
Listening Status:
ParameterTypeDescription
statusStringCurrent listening state. Example: "Listening for presence updates"
delegateCometChatUserDelegateActive delegate receiving events. Example: ViewController.self
Events Waiting:
EventDescription
onUserOnline(user:)Triggered when a subscribed user comes online
onUserOffline(user:)Triggered when a subscribed user goes offline

Stop Listening for Presence

CometChat.userdelegate = nil
Cleanup Configuration:
ParameterTypeDescription
userdelegateCometChatUserDelegate?Set to nil to stop receiving events. Example: nil
Listening Status:
ParameterTypeDescription
statusStringCurrent listening state. Example: "No longer listening for presence updates"

Check User Status

CometChat.getUser(UID: "cometchat-uid-2", onSuccess: { user in
    let status = user?.status // .online or .offline
    let lastActive = user?.lastActiveAt // Unix timestamp
}, onError: { error in
    print("Error: \(error?.errorDescription)")
})
Request Parameters:
ParameterTypeDescription
UIDStringUnique identifier of the user to check. Example: "cometchat-uid-2"
Success Response (User Object):
ParameterTypeDescription
uidString?Unique identifier of the user. Example: "cometchat-uid-2"
nameString?Display name of the user. Example: "George Alan"
avatarString?URL to the user’s avatar image. Example: "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"
linkString?URL to the user’s profile page. Example: nil
roleString?Role assigned to the user. Example: "default"
statusUserStatusCurrent online status of the user. Example: .online
statusMessageString?Custom status message set by the user. Example: nil
lastActiveAtDoubleUnix timestamp of the user’s last activity. Example: 1772110483.0
hasBlockedMeBoolIndicates if this user has blocked the logged-in user. Example: false
blockedByMeBoolIndicates if the logged-in user has blocked this user. Example: false
deactivatedAtDoubleUnix timestamp when user was deactivated (0 if active). Example: 0.0
tags[String]Array of tags associated with the user. Example: []
metadata[String: Any]?Custom metadata dictionary. Example: [:]
Error Response (CometChatException):
ParameterTypeDescription
errorCodeStringUnique error code identifying the error type. Example: "ERR_UID_NOT_FOUND"
errorDescriptionStringHuman-readable description of the error. Example: "User with the specified UID does not exist"

Get Online Users

let usersRequest = UsersRequest.UsersRequestBuilder()
    .set(limit: 30)
    .set(status: .online)
    .build()

usersRequest.fetchNext(onSuccess: { users in
    // All users in this list are online
}, onError: { error in
    print("Error: \(error?.errorDescription)")
})
Request Parameters:
ParameterTypeDescription
limitIntMaximum number of users to fetch. Example: 30
statusUserStatusFilter by online status. Example: .online
Success Response (Array of User Objects):
ParameterTypeDescription
uidString?Unique identifier of the user. Example: "cometchat-uid-1"
nameString?Display name of the user. Example: "Andrew Joseph"
avatarString?URL to the user’s avatar image. Example: "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"
linkString?URL to the user’s profile page. Example: nil
roleString?Role assigned to the user. Example: "admin"
statusUserStatusCurrent online status of the user. Example: .online
statusMessageString?Custom status message set by the user. Example: nil
lastActiveAtDoubleUnix timestamp of the user’s last activity. Example: 1772105474.0
hasBlockedMeBoolIndicates if this user has blocked the logged-in user. Example: false
blockedByMeBoolIndicates if the logged-in user has blocked this user. Example: false
deactivatedAtDoubleUnix timestamp when user was deactivated (0 if active). Example: 0.0
tags[String]Array of tags associated with the user. Example: []
metadata[String: Any]?Custom metadata dictionary. Example: [:]
Response Summary:
ParameterTypeDescription
typeStringResponse type. Example: "[User]"
countIntNumber of users returned. Example: 5
filterStringApplied filter. Example: "status = .online"
Error Response (CometChatException):
ParameterTypeDescription
errorCodeStringUnique error code identifying the error type. Example: "ERR_NOT_LOGGED_IN"
errorDescriptionStringHuman-readable description of the error. Example: "User is not logged in"

Get Offline Users

let usersRequest = UsersRequest.UsersRequestBuilder()
    .set(limit: 30)
    .set(status: .offline)
    .build()

usersRequest.fetchNext(onSuccess: { users in
    for user in users {
        let lastSeen = user.lastActiveAt // When user was last online
    }
}, onError: { error in
    print("Error: \(error?.errorDescription)")
})
Request Parameters:
ParameterTypeDescription
limitIntMaximum number of users to fetch. Example: 30
statusUserStatusFilter by offline status. Example: .offline
Success Response (Array of User Objects):
ParameterTypeDescription
uidString?Unique identifier of the user. Example: "cometchat-uid-1"
nameString?Display name of the user. Example: "Andrew Joseph"
avatarString?URL to the user’s avatar image. Example: "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"
linkString?URL to the user’s profile page. Example: nil
roleString?Role assigned to the user. Example: "admin"
statusUserStatusCurrent online status of the user. Example: .offline
statusMessageString?Custom status message set by the user. Example: nil
lastActiveAtDoubleUnix timestamp of the user’s last activity (use for “last seen”). Example: 1772105474.0
hasBlockedMeBoolIndicates if this user has blocked the logged-in user. Example: false
blockedByMeBoolIndicates if the logged-in user has blocked this user. Example: false
deactivatedAtDoubleUnix timestamp when user was deactivated (0 if active). Example: 0.0
tags[String]Array of tags associated with the user. Example: []
metadata[String: Any]?Custom metadata dictionary. Example: [:]
Response Summary:
ParameterTypeDescription
typeStringResponse type. Example: "[User]"
countIntNumber of users returned. Example: 30
filterStringApplied filter. Example: "status = .offline"
Sample User Entries:
uidnamestatuslastActiveAt
123Abc.offline1756196135.0 (26/08/25, 1:45 PM)
123abcAbc.offline1753957273.0 (31/07/25, 3:51 PM)
user177193848825aditya.offline1771941423.0 (24/02/26, 7:27 PM)
cometchat-uid-1Andrew Joseph.offline1772105474.0 (26/02/26, 5:01 PM)
cometchat-uid-5John Paul.offline1771416145.0 (18/02/26, 6:32 PM)
Error Response (CometChatException):
ParameterTypeDescription
errorCodeStringUnique error code identifying the error type. Example: "ERR_NOT_LOGGED_IN"
errorDescriptionStringHuman-readable description of the error. Example: "User is not logged in"

User List Presence

In other words, as a logged-in user, when I retrieve the user list, how do I know if a user is online/offline? When you fetch the list of users, in the User object, you will receive 2 fields:
  1. status - This will hold either of the two values:
    • .online - This indicates that the user is currently online and available to chat.
    • .offline - This indicates that the user is currently offline and is not available to chat.
  2. lastActiveAt - In case the user is offline, this field holds the timestamp of the time when the user was last online. This can be used to display the “Last seen” of the user if needed.
User Object with Presence Data:
ParameterTypeDescription
uidString?Unique identifier of the user. Example: "user1"
nameString?Display name of the user. Example: "Alice"
avatarString?URL to the user’s avatar image. Example: "https://example.com/alice.png"
statusUserStatusCurrent online status. Example: .online
lastActiveAtDoubleUnix timestamp of last activity. Example: 1699900000.0
Multiple Users Example:
uidnamestatuslastActiveAtDescription
user1Alice.online1699900000.0Currently online
user2Bob.offline1699800000.0Last seen timestamp

Calculating “Last Seen”

if user.status == .offline {
    let lastActiveDate = Date(timeIntervalSince1970: user.lastActiveAt)
    let timeAgo = Date().timeIntervalSince(lastActiveDate)
    
    let minutes = Int(timeAgo / 60)
    let hours = Int(timeAgo / 3600)
    let days = Int(timeAgo / 86400)
    
    if days > 0 {
        print("Last seen \(days) day(s) ago")
    } else if hours > 0 {
        print("Last seen \(hours) hour(s) ago")
    } else {
        print("Last seen \(minutes) minute(s) ago")
    }
}
Input Parameters:
ParameterTypeDescription
statusUserStatusUser’s current status. Example: .offline
lastActiveAtDoubleUnix timestamp of last activity. Example: 1772110483.0
Calculation Variables:
VariableTypeDescription
lastActiveDateDateConverted Date object from timestamp. Example: Date(timeIntervalSince1970: 1772110483.0)
timeAgoTimeIntervalSeconds since last activity. Example: 3600.0 (1 hour)
minutesIntMinutes since last activity. Example: 60
hoursIntHours since last activity. Example: 1
daysIntDays since last activity. Example: 0
Output Examples:
timeAgo (seconds)Output
300”Last seen 5 minute(s) ago”
3600”Last seen 1 hour(s) ago”
86400”Last seen 1 day(s) ago”
172800”Last seen 2 day(s) ago”

UserStatus Enum

ValueRaw ValueDescription
.online0User is currently online and available
.offline1User is offline, use lastActiveAt for “last seen”

Common Error Codes

Error CodeDescriptionResolution
ERR_NOT_LOGGED_INUser is not logged inLogin first using CometChat.login()
ERR_UID_NOT_FOUNDUser with specified UID does not existVerify the UID is correct
ERR_INVALID_LIMITInvalid limit value providedUse a limit between 1-100