Skip to main content
Key Benefit: Powerful message retrieval system that supports filtering by tags, message types, deletion status, and threading with real-time live collections for responsive chat interfaces.

Feature Overview

The getMessages function provides comprehensive message retrieval capabilities, allowing you to fetch messages from specific subchannels based on various criteria. This function returns a live collection that automatically updates when messages are added, modified, or deleted.

Advanced Filtering

Comprehensive query parameters
  • Filter by tags (including/excluding)
  • Message type filtering
  • Deleted message inclusion
  • Thread-based querying

Real-time Updates

Live collection benefits
  • Automatic data synchronization
  • Real-time message updates
  • Efficient pagination handling
  • Memory-optimized collections

Implementation Guide

  • Basic Message Querying
  • Threaded Message Querying
  • Jump to Specific Message
Retrieve messages from a subchannel with optional filteringQuery messages with various filtering options to get exactly the messages you need for your chat interface.

Required Parameters

ParameterTypeDescription
subChannelIdStringThe ID of the subchannel from which to retrieve messages

Optional Parameters

ParameterTypeDescription
includingTagsArray<String>Filter messages that contain at least one of the specified tags
excludingTagsArray<String>Exclude messages that contain any of the specified tags
includeDeletedBooleanWhether to include deleted messages in results (default: false)
typeMessageTypeFilter by specific message type (TEXT, IMAGE, FILE, AUDIO, VIDEO, CUSTOM)
sortOptionSortOptionSort order: firstCreated (oldest first) or lastCreated (newest first)

Code Examples

// Basic message query with tag filtering
let messageQueryOptions = AmityMessageQueryOptions(
    subChannelId: "subChannel-123", 
    includingTags: ["games"], 
    excludingTags: ["staff-only"], 
    sortOption: .lastCreated
)
let messagesCollection = messageRepository.getMessages(options: messageQueryOptions)

// Observe messages with real-time updates
token = messageRepository.getMessages(options: messageQueryOptions).observe({ collection, change, error in
    if let error {
        print("Error: \(error).")
        return
    }
    for message in collection.allObjects() {
        // Handle each message in the collection
    }
})
Sorting Options: Use firstCreated for chronological order (oldest first) or lastCreated for reverse chronological order (newest first, typical for chat interfaces).

Query Strategies

Filter messages using custom tags for categorizationUse includingTags and excludingTags to create sophisticated filtering systems:
  • Including Tags: Messages must have at least one of the specified tags
  • Excluding Tags: Messages with any of these tags will be filtered out
  • Combine Both: Create precise filters by including desired tags while excluding unwanted ones
Example use cases: Filter gaming-related messages while excluding staff-only content, or show only announcements while hiding archived discussions.
Query specific types of messages for specialized viewsFilter by message type to create focused interfaces:
  • Text Messages: AmityMessage.DataType.TEXT for text-only conversations
  • Media Messages: IMAGE, VIDEO, AUDIO for media galleries
  • File Messages: FILE for document sharing views
  • Custom Messages: CUSTOM for app-specific message types
This enables creation of specialized views like media galleries or document repositories within chat channels.
Handle threaded conversations and reply structuresImplement sophisticated conversation threading:
  • Top-Level Messages: Use messageParentFilter: nil or parentId: null for main conversation flow
  • Thread Replies: Use parentId to get all replies to a specific message
  • Thread Navigation: Combine with sorting to maintain chronological order within threads
Essential for implementing reply features, comment systems, and structured discussions.
Implement jump-to-message functionalityEnable users to navigate directly to specific messages:
  • Context Preservation: aroundMessageId provides surrounding messages for context
  • Error Handling: Gracefully handle invalid or deleted message targets
  • Pagination Strategy: Manage data source swapping when jumping between distant messages
Critical for implementing features like “jump to reply”, search result navigation, and deep linking to specific messages.

Best Practices

Optimize data loading and memory usage
  • Use appropriate page sizes (15-20 messages for mobile, ~40 for desktop)
  • Implement scroll-based pagination with threshold detection
  • Cache previous pages to enable smooth bidirectional scrolling
  • Monitor memory usage and release old pages when not needed
Proper pagination ensures smooth scrolling performance even in channels with thousands of messages.
Maintain data consistency with live collections
  • Always use live collections for active chat interfaces
  • Handle connection state changes gracefully
  • Implement proper cleanup when components unmount
  • Use appropriate error handling for network issues
Live collections automatically sync new messages, edits, and deletions without manual refresh calls.
Optimize query performance and user experience
  • Combine filters efficiently to reduce server load
  • Use specific message type filters when building specialized views
  • Implement proper loading states for better user experience
  • Cache frequently accessed message collections
Well-optimized queries provide faster response times and better scalability.
Implementation Strategy: Start with basic message querying using live collections, then add filtering capabilities as needed. Always implement proper error handling for network issues and invalid parameters to ensure robust chat experiences.