---
source_url: https://www.pubnub.com/docs/chat/swift-chat-sdk/build/features/users/mentions
title: Mention users
updated_at: 2026-06-16T12:48:55.372Z
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# Mention users

Tag users in chat messages with `@` mentions. Type `@` followed by at least three letters to see username suggestions.

:::tip Generic referencing
Channel references, user mentions, and links are instances of `MessageElement` with different `MentionTarget` types.
:::

**Configuration options:**

* **User source**: channel members or all app users
* **Suggestions**: up to 100 usernames (default: 10)
* **Username length**: up to [200 characters](https://www.pubnub.com/docs/sdks/swift/api-reference/objects#set-user-metadata)
* **Mentions per message**: up to 100 (default: 10)

Implementation follows similar patterns to [channel referencing](https://www.pubnub.com/docs/chat/swift-chat-sdk/build/features/channels/references) and [links](https://www.pubnub.com/docs/chat/swift-chat-sdk/build/features/messages/links).

:::note Requires App Context
To mention users from a keyset, you must [enable App Context](https://youtu.be/9UEoSlngpYI) for your app's keyset in the [Admin Portal](https://admin.pubnub.com/).
:::

## Add user mentions

Add user mentions with `@` followed by at least three letters (e.g., `@Mar`).

Mentioned users are stored in the [MessageDraft object](https://www.pubnub.com/docs/chat/swift-chat-sdk/learn/chat-entities/message-draft). When sent with `send()`, mention data is saved to 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()](https://www.pubnub.com/docs/chat/swift-chat-sdk/build/features/messages/drafts#add-message-element) method for details.

### Sample code

:::tip 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.

```swift
// Assumes a "ChannelImpl" reference named "channel"
// Create a message draft.
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()` removes a user mention from a [draft message](https://www.pubnub.com/docs/chat/swift-chat-sdk/build/features/messages/drafts).

### 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()](https://www.pubnub.com/docs/chat/swift-chat-sdk/build/features/messages/drafts#remove-message-element) method for details.

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

### Sample code

:::tip 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.

```swift
// Assumes a "MessageDraftImpl" reference named "messageDraft"
// 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 users matching a 3-letter string from channel members or global users.

##### Single listener

The message elements listener returns suggestions for channel references, user mentions, and links.

This listener monitors changes in a message draft through the `onChange` method, which takes `messageElements` and `suggestedMentions` as parameters.

* `MessageElements` represent the draft's current state and can include plain text or links, such as user mentions, channel references, or URLs. These elements are organized to reflect their order in the draft.
* `SuggestedMentions` operates as a `Future` object, asynchronously providing potential mentions when available.

Example: typing `Sam` returns `Samantha`, `Samir`, etc. Default limit: 10 users (max: 100).

### Method signature

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

Refer to the [addChangeListener()](https://www.pubnub.com/docs/chat/swift-chat-sdk/build/features/messages/drafts#add-message-draft-change-listener) method for details.

### Sample code

:::tip 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.

```swift
// Assumes a "ChannelImpl" reference named "channel"
// 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)")
      }
    }
  }
}
  
// Create a message draft
let messageDraft = channel.createMessageDraft(isTypingIndicatorTriggered: channel.type != .public)
// Instantiate the listener
let listener = UserMentionListener()
// Add the listener to the message draft
messageDraft.addChangeListener(listener)
```

## Get mentioned users

`getMessageElements()` returns all users mentioned in a message.

### Method signature

This method has the following signature:

```swift
message.getMessageElements()
```

### Sample code

:::tip 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.

```swift
// Assumes a "MessageImpl" reference 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
  }
}
  
if containsMentions {
  print("The message contains mentions.")
} else {
  print("The message does not contain any mentions.")
}
```

## Collect all user-related mentions

`getCurrentUserMentions()` retrieves all instances where the current user was mentioned in channels or threads. Use this to build a mentions feed.

### Method signature

This method has the following signature:

```swift
chat.getCurrentUserMentions(
    startTimetoken: Timetoken? = nil,
    endTimetoken: Timetoken? = nil,
    count: Int = 100
) async throws -> (mentions: [UserMentionDataWrapper<MessageImpl>], isMore: Bool)
```

#### Input

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| startTimetoken | Timetoken | Optional |  | [Timetoken](https://www.pubnub.com/docs/sdks/swift/api-reference/misc#time) delimiting the start of a time slice (exclusive) to pull messages with mentions from. For details, refer to the [Fetch History section](https://www.pubnub.com/docs/sdks/swift/api-reference/storage-and-playback#fetch-history). |
| endTimetoken | Timetoken | Optional |  | Timetoken delimiting the end of a time slice (inclusive) to pull messages with mentions from. For details, refer to the [Fetch History section](https://www.pubnub.com/docs/sdks/swift/api-reference/storage-and-playback#fetch-history). |
| count | Int | Optional | `100` | Number of historical messages with mentions to return in a single call. Since each call returns all attached message actions 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](https://www.pubnub.com/docs/sdks/swift/api-reference/storage-and-playback#methods). |

#### 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](https://www.pubnub.com/docs/general/setup/users-and-devices) 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. |

### Sample code

:::tip 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.

```swift
// Assumes a "ChatImpl" reference 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
  let theOldestMentionTimetoken = response.mentions.compactMap { $0.userMentionData.message?.timetoken ?? nil }.min()
    
  // Fetch the next historical mentions by using the timetoken of the oldest mention from the previous response
  // as the 'startTimetoken:' parameter for the subsequent call. Continue fetching in this way to retrieve
  // all items until the resulting array is empty
  if let theOldestMentionTimetoken, response.isMore {
    let nextHistoryResults = try await chat.getCurrentUserMentions(startTimetoken: theOldestMentionTimetoken)
  }
}
```

## Show notifications for mentions

`user.onMentioned()` monitors mention events on the current user. Use this to trigger pop-up notifications. You can also use `user.stream.mentions()` for an `AsyncStream`-based approach.

:::tip Events documentation
To read more about the events of type `Mention`, refer to the [Chat events](https://www.pubnub.com/docs/chat/swift-chat-sdk/build/features/custom-events#mention-events) documentation.
:::

### Method signature

```swift
user.onMentioned(
    callback: @escaping (Mention) -> Void
) -> AutoCloseable
```

The `Mention` struct carries the mention payload:

```swift
public struct Mention {
    public let messageTimetoken: Timetoken
    public let channelId: String
    public let parentChannelId: String?
    public let mentionedByUserId: String
}
```

##### Input

| Parameter | Description |
| --- | --- |
| `callback` *Type: `(Mention) -> Void`Default: n/a | Closure called with a `Mention` whenever the user is mentioned in a message. |

##### Output

| Parameter | Description |
| --- | --- |
| `AutoCloseable` | An object you must retain. When released or closed, the listener stops. |

### Sample code

:::tip 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.
:::

```swift
// Hold a strong reference to the returned "AutoCloseable"; otherwise, it will be canceled.
let stopMentions = user.onMentioned { mention in
  debugPrint("Mentioned in channel: \(mention.channelId) by user: \(mention.mentionedByUserId)")
}

// AsyncStream equivalent
Task {
  for await mention in user.stream.mentions() {
    debugPrint("Mentioned in channel: \(mention.channelId)")
  }
}

// To stop listening:
stopMentions.close()
```

## Get mentioned users (deprecated)

`mentionedUsers` property returns all users mentioned in a message.

### Method signature

This is how you can access the property:

```swift
message.mentionedUsers
```