> ## Documentation Index
> Fetch the complete documentation index at: https://cometchat-22654f5b-docs-ios-ui-kit-sdk-fixes.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Edit A Message

> Guide to editing sent messages using the CometChat iOS SDK with real-time edit events and missed edit handling.

<Info>
  **Quick Reference for AI Agents & Developers**

  * **Edit message:** `CometChat.edit(message:onSuccess:onError:)`
  * **Listen for edits:** `onMessageEdited(_:)` in message listener delegate
  * **Missed edits:** Use `MessagesRequest` with appropriate filters
  * **Related:** [Delete Message](/sdk/ios/delete-message) · [Send Message](/sdk/ios/send-message) · [Messaging Overview](/sdk/ios/messaging-overview)
</Info>

While [editing a message](/sdk/ios/edit-message) is straightforward, receiving events for edited messages with CometChat has two parts:

1. Adding a listener to receive [real-time message edits](/sdk/ios/edit-message#real-time-message-edit-events) when your app is running
2. Calling a method to retrieve [missed message edits](/sdk/ios/edit-message#missed-message-edit-events) when your app was not running

## Edit a Message

*In other words, as a sender, how do I edit a message?*

In order to edit a message, you can use the `editMessage()` method. This method takes an object of the `BaseMessage` class. At the moment, you are only allowed to edit `TextMessage` and `CustomMessage`. Thus, the `BaseMessage` object must either be a Text or a Custom Message.

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    let textMessage = TextMessage(receiverUid: "cometchat-uid-2", text: "Updated message", receiverType: .user)
    textMessage.id = 12345  // ID of message to edit

    CometChat.edit(message: textMessage, onSuccess: { (message) in
        print("Message edited: \(message)")
    }, onError: { (error) in
        print("Error: \(error.errorDescription)")
    })
    ```
  </Tab>
</Tabs>

The object of the edited message will be returned in the `onSuccess()` callback method of the listener. The message object will contain the `editedAt` field set with the timestamp of the time the message was edited. This will help you identify if the message was edited while iterating through the list of messages. The `editedBy` field is also set to the UID of the user who edited the message.

<Accordion title="Sample Payloads">
  <Tabs>
    <Tab title="Request">
      **Method:** `CometChat.edit(message:)`

      **Object Type:** TextMessage (before editing)

      | Parameter    | Type                     | Value               |
      | ------------ | ------------------------ | ------------------- |
      | id           | `Int`                    | `12345`             |
      | receiverUid  | `String`                 | `"cometchat-uid-2"` |
      | text         | `String`                 | `"Updated message"` |
      | receiverType | `CometChat.ReceiverType` | `0` (`.user`)       |
    </Tab>

    <Tab title="Success Response">
      **Object Type:** BaseMessage

      **Base Message Properties:**

      | Parameter       | Type                        | Value                                    |
      | --------------- | --------------------------- | ---------------------------------------- |
      | id              | `Int`                       | `12345`                                  |
      | muid            | `String`                    | `"1640000000000-abc123"`                 |
      | conversationId  | `String`                    | `"cometchat-uid-1_user_cometchat-uid-2"` |
      | senderUid       | `String`                    | `"cometchat-uid-1"`                      |
      | receiverUid     | `String`                    | `"cometchat-uid-2"`                      |
      | receiverType    | `CometChat.ReceiverType`    | `0` (`.user`)                            |
      | messageCategory | `CometChat.MessageCategory` | `0` (`.message`)                         |
      | sentAt          | `Int`                       | `1640000000`                             |

      **Edit-Specific Properties:**

      | Parameter | Type     | Value               |
      | --------- | -------- | ------------------- |
      | editedAt  | `Double` | `1640001000`        |
      | editedBy  | `String` | `"cometchat-uid-1"` |
      | updatedAt | `Double` | `1640001000`        |

      **Text Message Properties:**

      | Parameter | Type       | Value               |
      | --------- | ---------- | ------------------- |
      | text      | `String`   | `"Updated message"` |
      | tags      | `[String]` | `[]`                |
    </Tab>

    <Tab title="Error Response">
      **Object Type:** CometChatException

      | Parameter        | Type     | Value                                               |
      | ---------------- | -------- | --------------------------------------------------- |
      | errorCode        | `String` | `"ERR_PERMISSION_DENIED"`                           |
      | errorDescription | `String` | `"You do not have permission to edit this message"` |
    </Tab>
  </Tabs>
</Accordion>

### Add/Update Tags

While editing a message, you can update the tags associated with the Message. You can use the `tags` property to do so. The tags added while editing a message will replace the tags set when the message was sent.

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    let tags = ["pinned", "important"]
    let textMessage = TextMessage(receiverUid: "cometchat-uid-2", text: "Pinned message", receiverType: .user)
    textMessage.id = 12345
    textMessage.tags = tags

    CometChat.edit(message: textMessage, onSuccess: {...}, onError: {...})
    ```
  </Tab>
</Tabs>

<Note>
  Tags added while editing REPLACE existing tags on the message.
</Note>

<Accordion title="Sample Payloads - Edit with Tags">
  <Tabs>
    <Tab title="Request">
      **Method:** `CometChat.edit(message:)`

      | Parameter | Type       | Value                     |
      | --------- | ---------- | ------------------------- |
      | id        | `Int`      | `12345`                   |
      | text      | `String`   | `"Pinned message"`        |
      | tags      | `[String]` | `["pinned", "important"]` |
    </Tab>

    <Tab title="Success Response">
      **Base Message Properties:**

      | Parameter      | Type     | Value                                    |
      | -------------- | -------- | ---------------------------------------- |
      | id             | `Int`    | `12345`                                  |
      | conversationId | `String` | `"cometchat-uid-1_user_cometchat-uid-2"` |
      | senderUid      | `String` | `"cometchat-uid-1"`                      |
      | receiverUid    | `String` | `"cometchat-uid-2"`                      |

      **Edit-Specific Properties:**

      | Parameter | Type     | Value               |
      | --------- | -------- | ------------------- |
      | editedAt  | `Double` | `1640001000`        |
      | editedBy  | `String` | `"cometchat-uid-1"` |

      **Text Message Properties:**

      | Parameter | Type       | Value                     |
      | --------- | ---------- | ------------------------- |
      | text      | `String`   | `"Pinned message"`        |
      | tags      | `[String]` | `["pinned", "important"]` |
    </Tab>
  </Tabs>
</Accordion>

By default, CometChat allows certain roles to edit a message.

| User Role       | Conversation Type | Edit Capabilities |
| --------------- | ----------------- | ----------------- |
| Message Sender  | One-on-one        | Own messages only |
| Message Sender  | Group             | Own messages only |
| Group Owner     | Group             | All messages      |
| Group Moderator | Group             | All messages      |

***

## Real-time Message Edit Events

*In other words, as a recipient, how do I know when someone edits their message in real-time?*

To receive real-time edit events, implement `CometChatMessageDelegate`:

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    extension YourViewController: CometChatMessageDelegate {
        
        func onMessageEdited(message: BaseMessage) {
            print("Message edited: \(message.id)")
            print("Edited at: \(message.editedAt)")
            print("Edited by: \(message.editedBy ?? "")")
            
            if let textMessage = message as? TextMessage {
                print("New text: \(textMessage.text)")
            }
        }
    }

    // Register the delegate:
    CometChat.messagedelegate = self
    ```
  </Tab>
</Tabs>

<Accordion title="Sample Payloads - onMessageEdited">
  <Tabs>
    <Tab title="Callback Payload">
      **Method:** `onMessageEdited(message:)`

      **Object Type:** BaseMessage

      | Parameter          | Type             | Description                  |
      | ------------------ | ---------------- | ---------------------------- |
      | message            | `BaseMessage`    | The edited message object    |
      | message.id         | `Int`            | Message ID                   |
      | message.editedAt   | `Double`         | Unix timestamp when edited   |
      | message.editedBy   | `String?`        | UID of user who edited       |
      | message.text       | `String`         | New text (for TextMessage)   |
      | message.customData | `[String: Any]?` | New data (for CustomMessage) |
    </Tab>
  </Tabs>
</Accordion>

***

## Missed Message Edit Events

*In other words, as a recipient, how do I know when someone edited their message when my app was not running?*

When you retrieve the list of previous messages, for the message that was edited, the `editedAt` and the `editedBy` fields will be set. Also, for example, the total number of messages for a conversation is 100, and the message with message ID 50 was edited. Now the message with id 50 will have the `editedAt` and the `editedBy` fields set whenever it is pulled from the history. Also, the 101st message will be an `Action` message informing you that the message with id 50 has been edited.

When your app was not running, edited messages appear in two ways:

1. **Edited Message in History:** The message object has `editedAt` and `editedBy` fields set
2. **Action Message:** An `ActionMessage` is added to history indicating the edit

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    // Detect edited messages in history
    for message in messages {
        if message.editedAt > 0 {
            print("Message \(message.id) was edited at \(message.editedAt)")
            print("Edited by: \(message.editedBy ?? "unknown")")
        }
        
        if let actionMessage = message as? ActionMessage {
            if actionMessage.action == .messageEdited {
                print("Edit action detected")
                if let editedMsg = actionMessage.actionOn as? BaseMessage {
                    print("Edited message ID: \(editedMsg.id)")
                }
            }
        }
    }
    ```
  </Tab>
</Tabs>

<Accordion title="Sample Payloads - Action Message for Edit">
  <Tabs>
    <Tab title="Action Message Payload">
      **Object Type:** ActionMessage

      | Parameter | Type          | Description                         |
      | --------- | ------------- | ----------------------------------- |
      | action    | `String`      | `"edited"`                          |
      | actionOn  | `BaseMessage` | Updated message with edited details |
      | actionBy  | `User`        | User who edited the message         |
      | actionFor | `AppEntity`   | Receiver (User or Group)            |
    </Tab>
  </Tabs>
</Accordion>

<Note>
  In order to edit a message, you need to be either the sender of the message or the admin/moderator of the group in which the message was sent.
</Note>

***

## Success & Failure Responses

### Edit Message Success Response

When `edit()` is successful, the `onSuccess` callback returns the edited `BaseMessage` object:

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    CometChat.edit(message: textMessage, onSuccess: { (message) in
        // message: BaseMessage - The edited message object
        print("Message ID: \(message.id)")                 // Int - Message ID
        print("Edited At: \(message.editedAt)")            // Double - Edit timestamp
        print("Edited By: \(message.editedBy ?? "")")      // String? - UID of user who edited
        print("Sender UID: \(message.senderUid)")          // String - Original sender
        print("Sent At: \(message.sentAt)")                // Int - Original send timestamp
        
        // Get updated text
        if let textMessage = message as? TextMessage {
            print("Updated Text: \(textMessage.text)")     // String - New message text
        }
    }, onError: { (error) in
        // Handle error
    })
    ```
  </Tab>
</Tabs>

### Edit Message Failure Response

When `edit()` fails, the `onError` callback returns a `CometChatException`:

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    CometChat.edit(message: textMessage, onSuccess: { (message) in
        // Success
    }, onError: { (error) in
        print("Error Code: \(error.errorCode)")
        print("Error Description: \(error.errorDescription)")
        
        // Handle specific errors
        switch error.errorCode {
        case "ERR_NOT_LOGGED_IN":
            // User is not logged in
            break
        case "ERR_MESSAGE_NOT_FOUND":
            // Message with specified ID does not exist
            break
        case "ERR_PERMISSION_DENIED":
            // User doesn't have permission to edit this message
            break
        case "ERR_INVALID_MESSAGE_TYPE":
            // Cannot edit this message type
            break
        default:
            break
        }
    })
    ```
  </Tab>
</Tabs>

***

## Edited Message Properties

When a message is edited, these properties are set:

| Property    | Type      | Description                            |
| ----------- | --------- | -------------------------------------- |
| `editedAt`  | `Double`  | Unix timestamp when message was edited |
| `editedBy`  | `String?` | UID of user who edited the message     |
| `updatedAt` | `Double`  | Same as editedAt for edited messages   |

***

## Common Error Codes

| Error Code                 | Description            | Resolution                                       |
| -------------------------- | ---------------------- | ------------------------------------------------ |
| `ERR_NOT_LOGGED_IN`        | User is not logged in  | Login first using `CometChat.login()`            |
| `ERR_MESSAGE_NOT_FOUND`    | Message does not exist | Verify the message ID is correct                 |
| `ERR_PERMISSION_DENIED`    | No permission to edit  | Only sender or group admin/moderator can edit    |
| `ERR_INVALID_MESSAGE_TYPE` | Cannot edit this type  | Only TextMessage and CustomMessage can be edited |
