# Manage local conversations (/en/realtime-media/im/build/build-core-messaging/messages/manage-messages/ios)

> For AI agents: see the complete documentation index at [llms.txt](/llms.txt).

In chat apps, a conversation is composed of all the messages in a peer-to-peer chat, chat group, or chatroom. The Chat SDK supports managing messages by conversations, including retrieving and managing unread messages, deleting the historical messages on the local device, and searching historical messages.

    This page introduces how to use the Chat SDK to implement these functionalities.

    ## Understand the tech [#understand-the-tech-2]

    SQLCipher is used to encrypt the database that stores local messages. The Chat SDK uses `ChatManager` to manage local messages. The following are the core methods:

    * `getAllConversations`: Loads the conversation list on the local device.
    * `loadMessagesStartFromId`: Loads messages of a conversation.
    * `deleteMessage`: Deletes a message sent or received in a local conversation.
    * `deleteAllMessages`: Deletes all messages in a local conversation.
    * `removeMessagesStart`: Deletes messages sent and received in a certain period in a local conversation.
    * `AgoraChatConversation.unreadMessagesCount`: Retrieves the count of unread messages in the specified conversation.
    * `pinConversation`: Pins a conversation.
    * `getPinnedConversationsFromServerWithCursor`: Retrieves the pinned conversations from the server with pagination.
    * `deleteServerConversation`: Deletes a conversation from the server.
    * `AgoraChatConversation.loadMessagesStartFromId`: Searches for messages from the local database.
    * `AgoraChatConversation.insertMessage`: Inserts messages in the specified conversation.
    * `deleteAllMessagesAndConversations`: Clears the current user's chat history, including messages and conversations in individual chats, group chats, and chat rooms. You can also choose whether to clear the chat history on the server in one direction.

    ## Prerequisites [#prerequisites-2]

    Before proceeding, ensure that you meet the following requirements:

    * You have integrated the Chat SDK, initialized the SDK and implemented the functionality of registering accounts and login. For details, see [Chat SDK quickstart](../../../../get-started-sdk).
    * You understand the API call frequency limits as described in [Limitations](../../limitations).

    ## Implementation [#implementation-2]

    This section shows how to implement managing messages.

    ### Retrieve conversations [#retrieve-conversations-2]

    Call `getAllConversations` to retrieve all the conversations on the local device:

    ```objc
    NSArray *conversations = [[AgoraChatClient sharedClient].chatManager getAllConversations];
    ```

    ### Retrieve messages in the specified conversation [#retrieve-messages-in-the-specified-conversation-1]

    Refer to the following code sample to retrieve the messages in the specified conversation:

    ```objc
    // Retrieves the conversation ID
    AgoraChatConversation *conversation = [[AgoraChatClient sharedClient].chatManager getConversation:conversationId type:type createIfNotExist:YES];
    // Only one message is loaded during SDK initialization. Call loadMessagesStartFromId to retrieve more messages.
    NSArray *messages = [conversation loadMessagesStartFromId:startMsgId count:count searchDirection:MessageSearchDirectionUp];
    ```

    ### Retrieve the count of unread messages in the specified conversation [#retrieve-the-count-of-unread-messages-in-the-specified-conversation-1]

    Refer to the following code example to retrieve the count of unread messages:

    ```objc
    // Retrieves the ID of the specified conversation.
    AgoraChatConversation *conversation = [[AgoraChatClient sharedClient].chatManager getConversation:conversationId type:type createIfNotExist:YES];
    // Retrieves the count of unread messages.
    NSInteger unreadCount = conversation.unreadMessagesCount;
    ```

    ### Retrieve the count of unread messages in all conversations [#retrieve-the-count-of-unread-messages-in-all-conversations-1]

    Refer to the following code example to retrieve the count of all unread messages:

    ```objc
    NSArray *conversations = [[AgoraChatClient sharedClient].chatManager getAllConversations];
    NSInteger unreadCount = 0;
    for (AgoraChatConversation *conversation in conversations) {
      unreadCount += conversation.unreadMessagesCount;
    }
    ```

    ### Mark unread messages as read [#mark-unread-messages-as-read-1]

    Refer to the following code example to mark the specified messages as read:

    ```objc
    AgoraChatConversation *conversation = [[AgoraChatClient sharedClient].chatManager getConversation:conversationId type:type createIfNotExist:YES];
    // Marks all messages of the specified conversation as read.
    [conversation markAllMessagesAsRead:nil];
    // Marks the specified message as read.
    [conversation markMessageAsReadWithId:messageId error:nil];
    ```

    ### Clear chat history [#clear-chat-history-2]

    You can call the `deleteAllMessagesAndConversations:completion:` method to clear the current user's chat history, including messages and conversations in individual chats, group chats, and chat rooms. Additionally, you can choose whether to clear the chat history on the server. Note that clearing the chat history on the server means that you will not be able to retrieve conversations and messages from the server, although other users will not be affected.

    ```swift
    AgoraChatClient.shared().chatManager?.deleteAllMessagesAndConversations(true, completion: { err in
        if err == nil {
            // Succeeded in deleting conversations and messages in them.
        }
    })
    ```

    ### Delete all messages in a local conversation [#delete-all-messages-in-a-local-conversation-1]

    You can call `deleteAllMessages` to delete all messages in a local conversation:

    ```swift
    if let conversation = AgoraChatClient.shared().chatManager?.getConversationWithConvId("conversationId") {
        var err: AgoraChatError? = nil
        conversation.deleteAllMessages(&err)
         if let err = err {
             // Failed to delete messages
         } else {
            // Messages deleted successfully
         }
    }
    ```

    ### Delete messages in a local conversation by time period [#delete-messages-in-a-local-conversation-by-time-period-1]

    You can call `removeMessagesStart` to delete messages sent and received in a certain period in a local conversation.

    ```swift
    if let conversation = AgoraChatClient.shared().chatManager?.getConversationWithConvId("conversationId") {
        conversation.removeMessagesStart(startTime, to: endTime)
    }
    ```

    ### Delete a specific message [#delete-a-specific-message-1]

    You can delete a specific message from a local conversation. The sample code is as follows:

    ```swift
    if let conversation = AgoraChatClient.shared().chatManager?.getConversationWithConvId("conversationId") {
        var err: AgoraChatError? = nil
        conversation.deleteMessage(withId: "messageId", error:&err)
        if let err = err {
            // Failed to delete message
        } else {
            // Message deleted successfully
        }
    }
    ```

    ### Search for messages using keywords [#search-for-messages-using-keywords-1]

    Search methods provided on this page can be used to search the local database for all types of messages except command messages, because command messages are not stored in the local database.

    Call `loadMessagesWithKeyword` to search for messages by keywords, timestamp, and message sender:

    ```objc
    NSArray *messages = [conversation loadMessagesWithKeyword:keyword timestamp:0 count:50 fromUser:nil searchDirection:MessageSearchDirectionDown];
    ```

    ### Search for messages in all conversations based on search scope [#search-for-messages-in-all-conversations-based-on-search-scope-1]

    You can call the `AgoraChatManager#loadMessagesWithKeyword:timestamp:count:fromUser:searchDirection:scope:completion:` method to search in all conversations based on the search scope. This means that, in addition to setting the keywords, message timestamps, number of messages, sender, and search direction, you can also choose to search only in the message content, only in the message extension information, or in both.

    ```swift
    AgoraChatClient.shared().chatManager?.loadMessages(withKeyword: "keyword", timestamp: Int64((Date().timeIntervalSince1970 * 1000)), count: 100, fromUser: "", searchDirection: .up, scope: .content, completion: { messages, err in
        if err == nil {
            // Successfully retrieved messages.
        }
    })
    ```

    ### Search for messages in the current conversation based on search scope [#search-for-messages-in-the-current-conversation-based-on-search-scope-1]

    You can call `Conversation#loadMessagesWithKeyword:timestamp:count:fromUser:searchDirection:scope:completion:` method to search for messages in the current conversation based on the search scope. This means that, in addition to setting keywords, message timestamps, number of messages, sender, direction, and other parameters, you can also choose to search only in the message content, only in the message extension information, or in both.

    ```swift
    if let conversation = AgoraChatClient.shared().chatManager?.getConversationWithConvId("conversationsId") {
        conversation.loadMessages(withKeyword: "keyword", timestamp: 0, count: 50, fromUser: "", searchDirection: .down, scope: .content, completion: { messages, aError in

        })
    }
    ```

    ### Import messages [#import-messages-1]

    Call `importMessages` to import multiple messages to the specified conversation. This applies to use-cases where chat users want to formard messages from another conversation.

    ```objc
    [[AgoraChatClient sharedClient].chatManager importMessages:messages completion:nil];
    ```

    ### Insert messages [#insert-messages-1]

    If you want to insert a message to the current conversation without actually sending the message, construct the message body and call `insertMessage`. This can be used to send notification messages such as "XXX recalls a message", "XXX joins the chat group", and "Typing ...".

    ```objc
    // Inserts a message to the specified conversation.
    AgoraChatConversation *conversation = [[AgoraChatClient sharedClient].chatManager getConversation:conversationId type:type createIfNotExist:YES];
    [conversation insertMessage:message error:nil];
    ```

    ## Next steps [#next-steps-2]

    After implementing managing messages, you can refer to the following documents to add more messaging functionalities to your app:

    * [Retrieve conversations and messages from the server](./retrieve-messages)
    * [Message receipts](./message-receipts)

    
  
      
  
      
  
      
  
      
  
