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.

Generic referencing

Channel references, user mentions, and links are instances of MessageElement with different MentionTarget types.

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 and links.

Requires App Context

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

Add 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.

Whenever you mention a user, this user is added to the list of all mentioned users inside the MessageDraft object. This draft contains the text content and all mentioned users and their names from the selected user metadata source (all channel members or all users on the app's keyset). Once you send this message (send()), that information gets stored in the message metadata.

Method signature

You can add a user reference by calling the addMention() method with the target of MentionTarget.user.

Refer to the addMention() method for details.

Basic usage

Create the Hello Alex! I have sent you this link on the #offtopic channel. message where Alex is a user mention.

// Create a message draft
if let messageDraft = channel?.createMessageDraft(isTypingIndicatorTriggered: channel?.type != .public) {

// Update the text of the message draft
messageDraft.update(text: "Hello Alex! I have sent you this link on the #offtopic channel.")

// Add a user mention to the string "Alex"
let userMentionTarget = MentionTarget.user(userId: "alex_d")
messageDraft.addMention(offset: 6, length: 4, target: userMentionTarget)

// Additional logic can be implemented as needed
// For example, sending the draft or adding listeners
}

Remove user mentions

removeMention() lets you remove a previously added user mention from a draft message.

Method signature

You can remove user mentions from a draft message by calling the removeMention() method at the exact offset where the user mention starts.

Refer to the removeMention() method for details.

Offset value

If you don't provide the position of the first character of the message element to remove, it isn't removed.

Basic usage

Remove the user mention from the Hello Alex! I have sent you this link on the #offtopic channel. message where Alex is a user mention.

// assume the message reads
// Hello Alex! I have sent you this link on the #offtopic channel.`

// remove the channel reference
messageDraft?.removeMention(offset: 6)

Get user suggestions

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

icon

Single listener


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

You must add a message elements listener to receive user suggestions.

Refer to the addChangeListener() method for details.

Basic usage

Create a message draft and add a change listener to listen for user mentions.

// Create a message draft
if let messageDraft = channel?.createMessageDraft(isTypingIndicatorTriggered: channel?.type != .public) {

// Define the listener conforming to MessageDraftChangeListener protocol
class UserMentionListener: MessageDraftChangeListener {
func onChange(messageElements: [MessageElement], suggestedMentions: any FutureObject<[SuggestedMention]>) {
// Update UI with message elements
updateUI(with: messageElements) // updateUI is your own function for updating UI

// Asynchronously process suggested user mentions
suggestedMentions.async { result in
switch result {
case .success(let mentions):
updateUserMentionList(with: mentions) // updateUserMentionList is your own function for updating user mention suggestions
case .failure(let error):
show all 27 lines

Get mentioned users

To return all users mentioned in a message, use the getMessageElements() method.

Method signature

This method has the following signature:

message.getMessageElements()

Basic usage

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

// Assuming you have a message object
let message = // your message object

// Retrieve the message elements
let messageElements = message.getMessageElements()

// Check if any of the message elements are mentions
let containsMentions = messageElements.contains {
switch $0 {
case let .link(text, target):
if case let .user(userId) = target {
return true
} else {
return false
}
show all 25 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

Get mentioned users (deprecated)

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
Last updated on