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
Sample code
The code samples in Swift Chat SDK focus on asynchronous code execution.
You can also write synchronous code as the parameters are shared between the async and sync methods but we don't provide usage examples of such.
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.
// Assuming you have a reference of type "ChannelImpl" named "channel"
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"
messageDraft.addMention(offset: 6, length: 4, target: MentionTarget.user(userId: "alex_d"))
// 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
Sample code
The code samples in Swift Chat SDK focus on asynchronous code execution.
You can also write synchronous code as the parameters are shared between the async and sync methods but we don't provide usage examples of such.
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 user 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).
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
Sample code
The code samples in Swift Chat SDK focus on asynchronous code execution.
You can also write synchronous code as the parameters are shared between the async and sync methods but we don't provide usage examples of such.
Create a message draft and add a change listener to listen for user mentions.
// Define the listener conforming to MessageDraftChangeListener protocol.
// You can also use our ClosureMessageDraftChangeListener class to reduce the need for your custom types to implement the 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):
print("Error retrieving user mention suggestions: \(error)")
}
show all 25 linesGet 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
Sample code
The code samples in Swift Chat SDK focus on asynchronous code execution.
You can also write synchronous code as the parameters are shared between the async and sync methods but we don't provide usage examples of such.
Check if the message contains any mentions.
// Assuming you have a reference of type "MessageImpl" named "message".
// 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
}
default:
return false
show all 23 linesCollect all user-related mentions
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
) async throws -> (mentions: [UserMentionDataWrapper<MessageImpl>], isMore: Bool)
Input
Parameter | Description |
---|---|
startTimetoken Type: Timetoken Default: n/a | Timetoken delimiting the start of a time slice (exclusive) to pull messages with mentions from. For details, refer to the Fetch History section. |
endTimetoken Type: Timetoken Default: n/a | Timetoken delimiting the end of a time slice (inclusive) to pull messages with mentions from. For details, refer to the Fetch History section. |
count Type: Int Default: 100 | Number 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
Parameter | Description |
---|---|
(mentions: [UserMentionDataWrapper<MessageImpl>], isMore: Bool) Type: object | Returned object containing two fields: mentions and isMore . |
→ enhancedMentionsData Type: enhancedMentionsData (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. |
→ isMore Type: Bool | Info whether there are more historical events to pull. |
Basic usage
Sample code
The code samples in Swift Chat SDK focus on asynchronous code execution.
You can also write synchronous code as the parameters are shared between the async and sync methods but we don't provide usage examples of such.
List the last ten mentions for the current chat user.
// Assuming you have a reference of type "ChatImpl" named "chat"
Task {
// Fetch the first set of users.
// Since no 'startTimetoken' parameter is provided, we fetch the items starting from the current time
let response = try await chat.getCurrentUserMentions(count: 10)
response.mentions.forEach { mentionData in
debugPrint("Mention event: \(mentionData.userMentionData.event)")
debugPrint("Mentioned user: \(mentionData.userMentionData.userId)")
}
// The code below demonstrates how to fetch the next set of historical mentions. Skip it if you're only
// interested in the initial set.
// Retrieves the timetoken of the oldest mention from the previous response
show all 24 linesShow 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,
) -> AsyncStream<EventWrapper<T>>
Input
Parameter | Description |
---|---|
type *Type: T.Type Default: n/a | Type parameter allowing access to type information at runtime. |
channelId *Type: String Default: n/a | Channel to listen for new Mention events. |
customMethod Type: EmitEventMethod Default: n/a | An optional custom method for emitting events. If not provided, defaults to .publish . Available values: .publish and .signal . |
Output
Parameter | Description |
---|---|
AsyncStream<EventWrapper<T> | An asynchronous stream that emits a value each time a new event of the specified type is detected. |
Basic usage
Sample code
The code samples in Swift Chat SDK focus on asynchronous code execution.
You can also write synchronous code as the parameters are shared between the async and sync methods but we don't provide usage examples of such.
Print a notification for a mention of the current chat user on the support
channel.
// Assuming you have a reference of type "ChatImpl" named "chat"
Task {
if let user = try await chat.getUser(userId: "support_agent_15") {
for await update in chat.listenForEvents(type: EventContent.Mention.self, channelId: "support_agent_15") {
debugPrint("Mention payload: \(update.event.payload)")
}
} else {
debugPrint("User not found")
}
}
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