Mention users

The Mentions feature lets users tag specific individuals within a chat or conversation.

Swift Chat SDK lets one user tag another user by adding @ and typing at least three first letters of the username they want to mention. As a result, they get a list of suggested usernames when typing such a suggestion, like @Mar.

The list of returned users depends on your app configuration - these can be either all members in the channel where you write a message or all users of your app (user data taken from the Admin Portal keyset for your app). The number of returned suggested users for the mention also depends on your app configuration and can show up to 100 suggestions. The names of the suggested users can consist of multiple words and contain up to 200 characters.

You can configure your app to let users mention up to 100 users in a single message (default value is 10).

You can implement mentions in your app in a similar way you would implement channel referencing.

Requires App Context

To mention users from a keyset, you must enable App Context for your app's keyset in the Admin Portal.

Send message with user mentions

You can let users mention other users in a message by adding @ and typing at least three first letters of the username they want to mention, like @Mar.

Method signature

Head over to the sendText() method for details.

Basic usage

Mention Samantha and Samir (@Sam) in a message.

func mentionUsersExample(chat: ChatImpl) {
var mentionedUsers = MessageMentionedUsers()
mentionedUsers[0] = MessageMentionedUser(id: "101", name: "Samantha")
mentionedUsers[1] = MessageMentionedUser(id: "102", name: "Sam")

chat.getChannel(channelId: "support") {
switch $0 {
case let .success(channel):
channel?.sendText(
text: "Hello @Samantha and @Sam! Welcome to the team!",
mentionedUsers: mentionedUsers
) {
switch $0 {
case .success:
debugPrint("Message sent successfully with mentions!")
show all 24 lines

Get user suggestions

getUserSuggestions() returns all suggested users that match the provided 3-letter string from a selected data source (channel members or global users on your app's keyset).

For example, if you type Sam, you will get the list of users starting with Sam like Samantha or Samir. The default number of returned suggested usernames is 10 which is configurable to a maximum value of 100.

Method signature

This method can be called on two Swift Chat SDK objects and has the following signature:

  • Called on the Channel object

    channel.getUserSuggestions(
    text: String,
    limit: Int = 10,
    completion: ((Swift.Result<[MembershipImpl], Error>) -> Void)? = nil
    )
  • Called on the Chat object

    chat.getUserSuggestions(
    text: String,
    limit: Int = 10,
    completion: ((Swift.Result<[UserImpl], Error>) -> Void)? = nil
    )

Input

ParameterTypeRequiredDefaultDescription
textStringYesn/aAt least a 3-letter string typed in after @ with the user name you want to mention.
limitIntYes10Maximum number of returned usernames that match the typed 3-letter suggestion. The default value is set to 10, and the maximum is 100.

Output

TypeReturned on Channel objectReturned on Chat objectDescription
((Swift.Result<[MembershipImpl], Error>) -> Void)YesNoReturned list of Membership objects.
((Swift.Result<[UserImpl], Error>) -> Void)NoYesReturned list of User objects.

Basic usage

Return five channel users whose names start with Mar.

  • Called on the Channel object

    chat?.getChannel(
    channelId: "support"
    ) { result in
    switch result {
    case let .success(channel):
    if let channel = channel {
    debugPrint("Fetched channel metadata with ID: \(channel.id)")
    // Get user suggestions for "Sam" with a limit of 10 (default)
    channel.getUserSuggestions(text: "Sam") { result in
    switch result {
    case let .success(memberships):
    debugPrint("Fetched user suggestions:")
    memberships.forEach { membership in
    debugPrint("User ID: \(membership.user.id), Username: \(membership.user.name)")
    }
    show all 26 lines
  • Called on the Chat object

    chat.getUserSuggestions(text: "Sam") { result in
    switch result {
    case let .success(users):
    debugPrint("Fetched user suggestions:")
    users.forEach { user in
    debugPrint("User ID: \(user.id), Username: \(user.name)")
    }
    case let .failure(error):
    debugPrint("Failed to fetch user suggestions: \(error)")
    }
    }

Get mentioned users

You can access the mentionedUsers property of the Message object to return all users mentioned in a message.

Method signature

This is how you can access the property:

message.mentionedUsers

Basic usage

Check if the message with the 16200000000000000 timetoken contains any mentions.

/// Assuming you have a "chat" instance available
chat?.getChannel(
channelId: "support"
) {
switch $0 {
case let .success(channel):
if let channel = channel {
debugPrint("Fetched channel metadata with ID: \(channel.id)")
/// Timetoken for the message you're trying to get
let timetoken: Timetoken = 16200000000000000
/// Get the message with the specified timetoken
channel.getMessage(timetoken: timetoken) {
switch $0 {
case let .success(message):
if let message = message {
show all 36 lines

The getCurrentUserMentions() method lets you collect in one place all instances when a specific user was mentioned by someone - either in channels or threads. You can use this info to create a channel with all user-related mentions.

Method signature

This method has the following signature:

chat.getCurrentUserMentions(
startTimetoken: Timetoken? = nil,
endTimetoken: Timetoken? = nil,
count: Int = 100,
completion: ((Swift.Result<(mentions: [UserMentionDataWrapper<MessageImpl>], isMore: Bool), Error>) -> Void)?
)

Input

ParameterTypeRequiredDefaultDescription
startTimetokenTimetokenNon/aTimetoken delimiting the start of a time slice (exclusive) to pull messages with mentions from. For details, refer to the Fetch History section.
endTimetokenTimetokenNon/aTimetoken delimiting the end of a time slice (inclusive) to pull messages with mentions from. For details, refer to the Fetch History section.
countIntNo100Number of historical messages with mentions to return in a single call. Since each call returns all attached message reactions by default, the maximum number of returned messages is 100. For more details, refer to the description of the includeMessageActions parameter in the Swift SDK docs.

Output

ParameterTypeDescription
((Swift.Result<(mentions: [UserMentionDataWrapper<MessageImpl>], isMore: Bool), Error>)objectReturned object containing two fields: mentions and isMore.
 → enhancedMentionsDataenhancedMentionsData (ChannelMentionData or ThreadMentionData)Array listing the requested number of historical mention events with a set of information that differ slightly depending on whether you were mentioned in the main (parent) channel or in a thread.

For mentions in the parent channel, the returned ChannelMentionData includes these fields: event (of type Event<EventContent.Mention>), channelId where you were mentioned, message that included the mention, userId that mentioned you.

For mentions in threads, the returned ThreadMentionData includes similar fields, the only difference is that you'll get parentChannelId and threadChannelId fields instead of just channelId to clearly differentiate the thread that included the mention from the parent channel in which this thread was created.
 → isMoreBoolInfo whether there are more historical events to pull.

Basic usage

List the last ten mentions for the current chat user.

 // Create PubNub configuration
let pubNubConfiguration = PubNubConfiguration(
publishKey: "your-publish-key",
subscribeKey: "your-subscribe-key",
userId: "your-user-id"
// Add other required parameters
)

// Create Chat configuration
let chatConfiguration = ChatConfiguration(
// Fill in the necessary parameters for ChatConfiguration
)

// Create ChatImpl instance
let chat = ChatImpl(
show all 44 lines

Show notifications for mentions

You can monitor all events emitted when you are mentioned in a parent or thread channel you are a member of using the listenForEvents() method. You can use this method to create pop-up notifications for the users.

Events documentation

To read more about the events of type Mention, refer to the Chat events documentation.

Method signature

This method has the following parameters:

chat.listenForEvents<T: EventContent>(
type: T.Type,
channelId: String,
customMethod: EmitEventMethod = .publish,
callback: @escaping ((EventWrapper<T>) -> Void)
) -> AutoCloseable
Input
ParameterTypeRequiredDefaultDescription
typeT.TypeYesn/aType parameter allowing access to type information at runtime.
channelIdStringYesn/aChannel to listen for new Mention events.
customMethodEmitEventMethodNon/aAn optional custom method for emitting events. If not provided, defaults to .publish. Available values: .publish and .signal.
callback@escaping ((EventWrapper<T>) -> Void)Yesn/aA lambda function that is called with an EventWrapper<T> as its parameter. It defines the custom behavior to be executed whenever an event is detected on the specified channel.
Output
TypeDescription
AutoCloseableInterface that lets you stop receiving moderation-related updates (Moderation events) by invoking the close() method.

Basic usage

Print a notification for a mention of the current chat user on the support channel.

// Fetch metadata of the 'support_agent_15' user
chat.getUser(
userId: "support_agent_15"
) { result in
switch result {
case let .success(user):
if let user = user {
debugPrint("Fetched user metadata with ID: \(user.id)")
// Set up a listener for Mention events on the user's channel
let listener = chat.listenForEvents(
type: EventContent.Mention.self,
channelId: user.id
) { eventWrapper in
debugPrint("Received a mention for message \(eventWrapper.event.timetoken)")
}
show all 23 lines
Last updated on