arrow-left

Only this pageAll pages
gitbookPowered by GitBook
triangle-exclamation
Couldn't generate the PDF for 448 pages, generation stopped at 100.
Extend with 50 more pages.
1 of 100

Social+ Docs

Loading...

Loading...

Loading...

Getting Started

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Amity SDK

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Amity Social Cloud

Amity Social Cloud offers Chat and Social SDKs to streamline app development. Dive into our UI Kits and documentation to spark your creativity.

hashtag
Introduction

Amity is a technology infrastructure provider that builds ready-to-use social features that can be easily added to any app or website, including: Chat, Profile, Forum, Feed, Video Streaming, Stories, and more.

With Amity’s white-label APIs and SDKs, companies can build thriving communities and grow user engagement, without the hassle of deploying and maintaining any server infrastructure.

Let users create engaging content and engage with others through comments and reactions. Users can follow other users or topics and become members of various groups to get a personalized timeline of content. Activity feeds are also a great feature to directly engage with users. You can communicate with your users directly by posting important messages as announcements.

hashtag
Features

  • Connect users through formation of communities

  • Boost user engagement by user-generated posts/comments in communities

  • Personalize the feed based on user’s membership to different groups and communities

hashtag
Explore Our Products

Enable comments on posts within your application, seamlessly
  • Support multiple messaging formats when posting content

  • Manage & moderate communities and users in admin panel

  • Filter out content that includes profanity using our auto-block tools

  • React to user-generated content with our reaction tools

  • Assign roles and permissions on a role-based system.

  • Announcements

    Release notes, key changes and deprecation notices

    hashtag
    Behavioral Change Announcement

    We are excited to inform you about the recent updates we have made to our product to enhance your experience. These changes are scheduled for deployment as follows: 🔜 9th August: SG Region 🔜 10th August: EU & US Region. The best part is that these modifications will take effect immediately without requiring any action from your end to update the version.

    Now, let's take a look at what will be changed:

    1. Post creators will still have the ability to view their own soft-deleted posts.

    2. Admins/Super Admins will still retain the privilege to view user's soft-deleted posts.

    3. Non-Admin users, however, will no longer be able to access soft-deleted posts of other users.

    4. Moderators & Global Moderators, will also no longer be able to access soft-deleted posts of other users.

    Should you have any concerns or questions regarding these changes, please do not hesitate to reach out to us. We value your feedback and are here to assist you!

    hashtag
    API Deprecation Notice: v3/files for Image Moderation

    We'd like to announce that we will be deprecating v3/files API in favor of v4/images API for our image moderation feature. Effective 1 January 2024, v3/files will no longer support image moderation. If you are using v3/files to upload images, we recommend that you switch to using v4/images instead.

    To ensure a smoother transition process, we have already updated the iOS and Android SDKs in version 6.6.0, as well as Flutter SDK beta 0.21.0 to point to the new endpoint for uploadImage(). Therefore, if you wish to continue using the image moderation feature, you will need to upgrade to Android or iOS SDK 6.6.0 or higher; or Flutter beta 0.21.0 before 1 January 2024. After this date, v3/files and any SDKs below the aforementioned versions will no longer support image moderation. There is no impact to TypeScript SDK users as the SDK is already using v4/images.

    What this means if you wish to continue having images moderated:

    • Android & iOS: You will need to upgrade to Android or iOS SDK 6.6.0 or higher (or UIKit 3.1.0 or higher), before 1 January 2024. After this date, v3/files and any SDK version below 6.6.0 (or UIKit 3.0.0 and below) will no longer support image moderation

    • Flutter: You will need to upgrade to Flutter SDK beta 0.21.0 or higher, before 1 January 2024. After this date, v3/files and any SDK version below beta 0.21.0 will no longer support image moderation

    If you have any concerns or questions about this deprecation notice, please do not hesitate to contact our support team.

    hashtag
    RxJava2 and PagedList Deprecation Notice

    20 October 2022

    Today we are announcing the deprecation of RxJava2 and PagedList for Amity Android SDK, as we will be migrating from RxJava2 to RxJava3 and from PagedList to PagingData, effective January 1, 2023.

    hashtag
    What this means:

    • If you are using RxJava2 and PagedList, the last version that supports them (which will be released in December 2022) will continue to be maintained until 31 October 2023.

    • From 1 November 2023, Rxjava2 and PagedList will no longer be supported.

    Although we will not stop supporting RxJava2 and PagedList until October 2023, we recommend that you start planning your upgrade around Q4 2022, from RxJava2 to RxJava3 and from PagedList to PagingData.

    Separately, we will also be upgrading our SDK to support RxJava3 and PagingData in the coming weeks. Once the upgrade is complete, we will remove RxJava2 and PagedList from future versions of the SDK.

    hashtag
    Objective-C Deprecation Notice & Minimum Target Upgrade to iOS 13

    Updated: 19 September 2022

    Today we are announcing the deprecation of Objective-C for Amity iOS SDK as we will be migrating from Objective-C to pure Swift, effective 1 January 2023.

    What this means:

    • If you're using Objective-C to build your app, the last version that supports Objective-C (that will be published in December 2022) will continue to be maintained until 30 September 2023.

    • Starting 1 October 2023, Objective-C will no longer be supported.

    Although we will only be ending the support of Objective-C in October 2023, we recommend that you start planning the upgrade around Q4 2022.

    Xcode 14 Upgrade & Minimum Deployment Target Upgrade from iOS 12 to iOS 13

    Separately in the coming weeks, we will also be upgrading our SDK to support Xcode 14, and will be raising the minimum deployment target from iOS 12 to iOS 13. Once the minimum target upgrade occurs, we will be dropping iOS 12 & Xcode 13 support from future versions of the SDK.

    What’s in store with iOS 13+ upgrade:

    There are many new enhancements coming along with this upgrade, such as async/await APIs that help you to work easier with asynchronous programming. Migrating to Swift also comes as a cost-effective method in developing and maintaining your projects.

    hashtag
    Managed UI Kit Deprecation Announcement

    Updated: 21 June 2022

    Amity Social Cloud will be deprecating all managed versions of the UI Kits (IOS, Android and Web J.S.) on 31 August 2022 as requests to be able to further customize their look and feel have increased. Our UI Kits were built to enable even faster integration of our social and chat features. In January this year, we open sourced all our UI Kits to provide our customers with more flexibility and greater customization options. Since then, we have seen a shift towards the open source version as it gives complete control over the visual style while keeping the integration time as short as possible.

    To ensure that you continue to receive the latest updates and improvements, we encourage you to migrate over to the open source version. We’ve written instruction guides to help you migrate to the open source version, get the latest updates, and contribute to the project all available below.

    hashtag
    What happens once the managed version UI Kit is deprecated?

    Once the managed version is deprecated, we will transition our support to the open source UI Kit for any bug requests and releases of new features. You will still be able to use the managed UI Kit, however it will no longer be receiving further updates. All documentation relating to the managed UI Kit version will be moved to the deprecation notice section. Any ongoing improvements will be made to the open source version under the Lesser General Public License (GNU).

    hashtag
    How to migrate off the managed version UI Kit?

    hashtag
    iOS SDK Breaking Changes

    Updated: 09 December 2021

    From 09 Dec 2021 onwards, Amity iOS SDK will no longer maintain versions which were built with Xcode version prior to 13. and SDK v5.8 will be the first version that is built with Xcode 13 and the iOS 15 SDK.

    What drove the change?

    According to Apple’s announcement , "Starting April 2022, all iOS and iPadOS apps submitted to the App Store must be built with Xcode 13 and the iOS 15 SDK."

    When is the deadline I need to make the change?

    • From now to April 2022, you will be able to submit an app to App Store with Amity iOS SDK version prior to v5.8. but it’s highly recommended to plan the upgrade.

    • From April 2022 onwards, you will NOT be able to submit an app to App Store with Amity iOS SDK version prior to v5.8

    What’s the impact to my users who are currently using the app with Amity iOS SDK version prior to v5.8?

    There is no impact from the functionality wise for the users who are using your App under old Amity iOS SDK. However beginning form April 2022, developers can only submit an app to App Store with the following requirement.

    • Built with Xcode 13

    • Built with iOS 15 SDK

    • Built with Amity iOS SDK v5.8

    hashtag
    Maintenance Strategy for Breaking Changes

    Updated: 27 April 2021

    • and UIKit 1.12 will be the last version to contain the prefix Eko. New features WILL NOT be added to these older versions any longer.

    • We will only maintain these older versions for critical issues and bug fixes. Whenever a hot-fix is made available, it will be rerouted back to historical ASC SDK & UIKit, respectively, regardless of the current latest versioning.

    • Amity Social Cloud's SDK 5.0 and UIKit 2.0 will be introduced as a modularized category of changes and advancement. New features will only be added to these versions and those to come, above i.e. v5.1, v5.2 and so on and so forth.

    You can find more information about these changes in the respective changes for each platform, which you can access using the links below.

    ​​ ​​

    hashtag
    Follow / Unfollow Limited Availability Announcement

    Updated: 26 April 2021

    After the launch of our Amity Social features that allow customers around the world to build their own social network and grow their own community of users within the safety net of their own brands, our customers and the community they have built has grown much quicker than we originally anticipated - from building a community of travelers to engaging sports-fans around the world.

    In order to handle the massive spike in workloads from the growing number of customers while making sure our system always perform at the highest standard from both data latency and scalability aspects, we have decided to revert Follow and Unfollow features into Limited Availability release.

    The feature will be temporarily unavailable to all new customers while we work on upgrading our infrastructure and underlying deployment architecture. Starting from 26 April 2021, new SDK downloads will no longer contain follow/unfollow function and newly-generated API key will not be able to use the features. User profile, groups and feed features will remain unaffected. Existing customers who are already using the feature should also remain unaffected.

    Our priority is to ensure we scale our system architecture to meet the increasing demand from our existing customers who are using the system to actively grow their community. Our engineering team is working to bring these features back to General Availability release by June 2021. Thank you for your understanding and we apologize for any inconvenience this may have caused to our onboarding customers.

    hashtag
    iOS SDK Breaking Changes

    Updated: 08 December 2020

    From 1st Feb 2021 onwards, Amity iOS SDK will no longer maintain versions which were built with Xcode version prior to 12, and v4.2 will be the first version with Xcode 12 support. Please kindly plan ahead and upgrade your iOS SDK version if you are using the versions prior to v4.2

    What drove the change?

    According to Apple’s announcement , "Starting April 2021, all iOS and iPadOS apps submitted to the App Store must be built with Xcode 12 and the iOS 14 SDK."

    When is the deadline I need to make the change?

    • From now to 31st Jan, no impact but it’s highly recommended to plan the upgrade.

    • From 1st Feb onwards, Amity will no longer provide customer support regarding iOS SDK versions prior to v4.2

    • From 1st Feb to 31st Mar, you will still be able to submit an updated version to App Store with Amity iOS SDK version prior to v4.2

    What’s the impact to my users who are currently using the app with Amity iOS SDK version prior to v4.2?

    There is no impact from the functionality wise for the users who are using your App under old Amity iOS SDK, but they will NOT be able to get any further updated version from App Store unless you submit a new version which is :

    • Built with Xcode 12

    • Built with iOS 14 SDK

    • Built with Amity iOS SDK v4.2

    I want to upgrade Amity SDK but how do I know the changes between my current SDK version and the latest version?

    Please refer to this section for details.

    Install JavaScript SDK

    The Amity Social Cloud SDK for JavaScript is delivered as an npm module.

    hashtag
    Installation

    Add the SDK to your repository via npm: npm install @amityco/js-sdk --save.

    Installing the SDK requires you to use a javascript package manager such as npm

    Core Concepts

    hashtag
    Our Core Concepts section will outline functionality and information that is pertinent to all of our Chat SDK Modules.

    The following concepts are shared across all platforms and thus are centralized in this section for your ease of navigation and use.

    Channel Push Notification Settings

    The SDK offers push notification settings per channel, allowing users to configure whether to enable or disable push notifications for specific channel. This configuration applies universally to every device logged in as the same user.

    hashtag
    Get Channel Push Notification Settings

    The SDK provides "getSettings()" function within Channel Notification to check whether push notification is enabled on the channel.

    Install Flutter SDK (Beta)

    The Amity Social Cloud SDK for Flutter is available on PubDev

    hashtag
    Installation

    Add the SDK to your repository by adding amity_sdk depedency

    With Flutter:

    This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get

    Push Notification Toggles

    The SDK has three levels of notifications and in order for it to be sent, a notification has to pass throughout all three levels.

    • Network Level: (via Admin Panel) turning off notifications at this level effectively disable push notifications altogether for all of your customers.

    • User Level: (via client) A user can choose to enable/disable notifications per feature module. Please note that this setting is per user, not per device: regardless of which device sets this toggle, the new preference will take effect in all the devices where the user is logged in.

    Channel or Community Level: (via client) A user can choose to enable/disable notifications per channel or community (where is member of). Again, this preference is per user, not per device.

    circle-info

    In addition to push notifications, we also offer a Notification Tray that stores the notification history for each user.

    Live Objects

    Push Notification

    Live Messages

    Amity Collection

    Session State
    Users/Permissions
    SDK
    UIKit
    Analytics & Moderation

    Moderation

    Moderation is an important feature for building a safe community that encourages user participation and engagement.

    Amity’s customer-centric nature ensures that security needs are kept at the forefront of the work we do. Our purpose has been to continuously develop features that are safe and ready to use. We power our moderators with tools to control and impose permissions that make their applications a safer place, for all users. We put the utmost importance on giving power to our clients to implement protocols that keep their applications healthy, safe and compliant.

    circle-info
    1. The channel creator is automatically assigned as the channel moderator.

    2. The previous/last moderator is not allowed to leave a community and an error is displayed.

    3. The channel moderator can promote a user/member to moderator.

    4. The channel moderator can demote a moderator to a user/member.

    This applies only to Live and Community channels’. This does not apply to Conversation Channel.

    ChannelModeration class provides various methods to moderate the users present in channel. You can ban/unban users, assign roles or remove them from a user.

    or
    yarn
    . If your current build system does not use package managers, please contact us at
    .

    If you already installed our SDK with the name eko-sdk, be sure to check our migration guide from version 4 to 5.

    hashtag
    Browser Support

    • Chrome: 38+

    • Firefox: 42+

    • Microsoft Edge: 13+

    • Safari: 9+

    • Opera: 25+

    triangle-exclamation

    Amity Web SDK probably won't work great in Internet Explorer 11. We generally support the recent versions of major browsers listed above.

    Since Amity Web SDK uses local cache for performance and user experience reason, server side rendering is not supported. To use Amity Web SDK with NextJS, Amity Web SDK must be imported using Dynamic Import with SSR disabledarrow-up-right.

    circle-exclamation

    AmitySDK already includes our UIKit. Don’t install the UIKit separately if you have already installed the SDK.

    community.amity.coarrow-up-right
    ) :

    Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

    The minimum deployment target is:

    • iOS: iOS 9.0

    • Android: Android 4.4 (API Level 19)

     $ flutter pub add amity_sdk
    dependencies:
      amity_sdk: ^0.22.0
    TypeScript: There is no impact to TypeScript SDK users as the TS SDK is already using v4/images
  • EkoSDK 4.8 and UIKit 1.12 will be supported for critical issues for a period of 6 months. After which the window period will expire and EkoSDK 4.8 and UIKit 1.12 will be officially discontinued and no longer supported moving forward.

  • From April onwards, you will NOT be able to submit an updated version to App Store with Amity iOS SDK version prior to v4.2

    iOS Open Source Migration Guidearrow-up-right
    Android Open Source Migration Guidearrow-up-right
    Web JavaScript Open Source Migration Guidearrow-up-right
    herearrow-up-right
    EkoSDK 4.8arrow-up-right
    arrow-up-right
    iOS
    arrow-up-right
    Android
    arrow-up-right
    Web
    herearrow-up-right
    announcement

    The functionality isn't currently supported by this SDK.

    hashtag
    Update Channel Push Notification Settings

    The SDK provides "enable()" and "disable()" functions where user can choose whether to enable or disable push notifications coming from the channel.

    The functionality isn't currently supported by this SDK.

    hashtag

    Intall TypeScript SDK

    The Amity Social Cloud SDK for TypeScript is delivered as an npm module.

    hashtag
    Installation

    Add the SDK to your repository with this code:

    npm:

    yarn:

    hashtag
    Getting Started

    The very first thing to do once you have installed the SDK, is to creating an instance of the client and logging in.

    Once the client has been instantiated and you are logged in. You can now use API's to create a , , and !

    hashtag
    Browser Support

    • Chrome: 38+

    • Firefox: 42+

    • Microsoft Edge: 13+

    triangle-exclamation

    Amity Web SDK probably won't work great in Internet Explorer 11. We generally support the recent versions of major browsers listed above.

    Since Amity Web SDK uses local cache for performance and user experience reasons, server side rendering is not supported. To use Amity Web SDK with NextJS, Amity Web SDK must be imported using .

    hashtag
    React Native Framework

    Use our TypeScript SDK natively to support your applications built using the React Native framework.

    In order to support older JavaScript runtime, you need to include a global polyfill for your bundled package.

    First, install core-js in your project.

    Then, import fromEntries in the root of your project.

    circle-info

    You can check out our React Native sample application .

    Create User

    In Amity SDK, creating a new user can be done through the login method. Once the user account has been created, the user can then log into the app using their userId and displayName using the SDK's social and chat features.

    You may need to create a new user account via the SDK, such as when integrating the SDK with an existing user authentication system. In these cases, you can use the login method. Here's how the login method works:

    • If a user already exists for the specified userId, the SDK will log the user into the app using the provided userId. The displayName parameter can be updated upon calling the login method. If the displayName parameter is not provided, the system will retain the existing user's displayName.

    • If a user account does not already exist for the specified userId, the SDK will automatically create a new user account with the provided displayName and log the user into the app. If displayName is not provided, the userId will be used as displayName.

    circle-info

    Note:

    • When user edits / adds their display name, it can be up to 100 characters in length.

    Version 6 and Beta(v0.0.1)

    User Token Management

    API token management is a login authentication process that allows an amity user to access amity applications in a unified and streamlined environment.

    Amity SDK provides AmityUserTokenManager to manage user credentials. This includes an access token that can be used to access some Beta features.

    circle-info

    NOTE: Please be aware that we do not provide any API to support the usage of user tokens on the client SDK. To use this user token, you must interact with ASC services with your own effort.

    hashtag
    Create a User Token

    To create a new user token, refer to the following example and the parameters are.

    • userId: This is a required parameter of type String that represents the unique identifier of the user whose credentials are being managed by the AmityUserTokenManager.

    • displayName : This is an optional parameter of type String that represents the display name of the user. If provided, it will be associated with the user's credentials.

    Version 6 and Beta(v0.0.1)

    Files, Images, and Videos

    File upload and download are key features of our product, which enable developers to easily incorporate file-sharing functionality into their applications. With support for a wide range of file types, including images, videos, audio, and documents, developers can create highly engaging and interactive user experiences that drive engagement and increase retention. The maximum file size of a file regardless of its type is 1 GB.‌

    By enabling users to share files directly within the chat or social feed, developers can create highly personalized and engaging experiences that foster deeper connections among users. For example, users can share photos and videos with friends and family, or exchange documents and other files within a community. To support various use cases and make it easy to handle files, images, and videos, we offer convenient methods for managing these types of content:

    • File Handling

    circle-info

    The SDK does not manage the caching of any images or files. It is recommended to effectively handle caching to ensure optimal performance. You can use a pre-existing implementation or library to handle the caching of files or images.

    Chat Realtime Events

    In the context of channels, subchannels, and message collections, receiving real-time events is an automatic process for conversation and community channels; you do not need to perform any additional actions. However, for a live channel still needs to be established.

    Similar to the process for social real-time events, a topic is a unique path that must be constructed for each model you wish to receive updates about in real-time. The SDK offers helper methods for creating these topics for each model type. Each topic includes an events enum that developers can select to subscribe to, based on their business context and preferences.

    To receive updates from a channel or any content created within that channel, the user must hold 'Member' status within that channel. Once the user leaves the channel, they will no longer receive real-time events.

    hashtag
    Subchannel Topic

    We don't support this feature in JS SDK.

    Version 6 and Beta(v0.0.1)

    The functionality isn't currently supported by this SDK.

    d

    Community Push Notification Settings

    The SDK offers push notification settings per community, allowing users to configure which notification events should be enabled on the community. This configuration applies universally to every device logged in as the same user.

    Configurable events include POST_CREATED, POST_REACTED, COMMENT_CREATED, COMMENT_REACTED, COMMENT_REPLIED, STORY_CREATED, STORY_REACTED, STORY_COMMENT_CREATED

    hashtag
    Get Community Push Notification Settings

    The SDK provides "getSettings()" function within Community Notification to inspect which notification events are enabled on the community.

    The functionality isn't currently supported by this SDK.

    hashtag
    Update Community Push Notification Settings

    The SDK provides "enable()" function where user can choose which notification events to be enabled on the community and "disable()" function to disable all notification events on the community.

    The functionality isn't currently supported by this SDK.

    Heartbeat Sync

    The presence heartbeat is a mechanic to signal the system whether a user is online or offline. The SDK offers two convenient methods that allow users to periodically sync or unsync their presence status with the server. When the server receives a heartbeat sync request, it records the timestamp at the time of the request, designating it as the lastHeartbeat timestamp for that user.

    The SDK automatically manages the periodic syncing of this heartbeat once the startHeartbeat method is called. To cease syncing your presence with the server, the user must invoke the stopHeartbeat method.

    hashtag
    Start Heartbeat

    Invoke the startHeartbeat method in client.presence to initiate the heartbeat synchronization process. This method automatically checks the user's presence settings within the network, and if enabled, begins to sync the heartbeat at specified intervals defined in the SDK. The synchronization process is handled automatically, streamlining the user's interaction with the system.

    circle-info

    The heartbeat sync interval is determined automatically by SDK. Normally you can except heartbeat to be synced every 20-30 seconds.

    hashtag
    Stop Heartbeat

    Utilize the stopHeartbeat() method within client.presence to cease the heartbeat synchronization process. To restart the sync, you must invoke the startHeartbeat() method again.

    Get Channel

    hashtag
    Get a Channel

    The function allows users to retrieve information about a specific channel using the channelId parameter. This function returns a Live Object of the AmityChannel class, which contains information such as the channel's display name, tags, avatar, and other metadata.

    This function is useful for a variety of purposes, such as displaying information about a channel to users or retrieving channel details before joining the channel.

    Version 6 and Beta (v0.0.1)

    User Unread Count

    hashtag
    User Unread Count

    This function enables users to obtain the current user's total count of unread messages and their mention status across all channels and sub-channels. To retrieve this value, utilize the CoreClient and follow the code pattern below.

    circle-info

    Please note that the TypeScript SDK does not yet support retrieving mention status information with this function.

    Start / Stop reading a Subchannel

    To ensure that the message read count is up to date for a subchannel, users need to start reading the sub channel. When a user opens a subchannel, the chat system updates the read count for all messages in that channel, based on the user's reading status. This feature is designed to provide accurate read counts for sub channels, ensuring that users have a clear understanding of which messages have been read and which are still unread

    hashtag
    Start reading a sub channel

    Active reading of a subchannel and letting the chat system know that reading status can update the message read count in that sub channel. The system will update the read count for all messages in the sub channel that the user has not yet read.

    hashtag
    Stop reading a sub channel

    To maintain an accurate message read count, users should stop reading a sub channel when they have finished reading it. The chat system updates the read count based on the user's reading status, so if a user leaves a sub channel, they should stop reading to avoid reading new messages.

    circle-info

    stopReading will be called automatically if the internet connection drops or is disconected. It lasts for one minute. This means that if an internet connection drops after one minute, stopReading will be automatically called, and after it is re-established, startReading will be called again.

    User Push Notification Settings

    The SDK offers push notification settings per user, allowing users to configure whether to enable or disable push notifications for specific feature modules. This configuration applies universally to every device logged in as the same user.

    Configurable modules include CHAT, SOCIAL, and LIVE_STREAM.

    hashtag
    Get User Push Notification Settings

    The SDK provides "getSettings()" function within User Notification to inspect the current settings of each feature module.

    The functionality isn't currently supported by this SDK.

    hashtag
    Update Push Notification Settings

    The SDK provides "enable()" function where user can specify the settings of each module and "disableAll()" function where user can choose to disable notifications on every module.

    The functionality isn't currently supported by this SDK.

    Mark Channel as Read

    hashtag
    Mark Channel as Read

    Clearing all unread counts in a channel is a useful feature that allows users to easily keep track of their message history. To accomplish this, the SDK provides a convenient method to mark all messages within a channel as read, effectively clearing the unread count. This method can be called by invoking the markAsRead() function on the ChannelRepository class with the appropriate channelId parameter.

    Once called, the function will iterate through all messages in subchannels within the specified channel and mark each as read. This process will clear the unread count.

    Please note that clearing unread counts in a channel only applies to the specified channel and does not affect any other channels or subchannels. Additionally, clearing unread counts does not delete any messages or modify their content in any way. It simply updates their status to reflect that they have been read by the user.

    Unread Count

    The unread count feature in chat channels and subchannels allows you to keep track of new messages and stay up-to-date with ongoing conversations. By providing a simple indicator of unread messages, users can quickly prioritize which channels require their attention. This topic provides instructions for managing unread messages in a chat channel and sub-channel.

    circle-info

    Note: we only support unread count on community, conversation, and broadcast channels. We do not support this feature in live channels. Mention unread in channels and subchannels aren't supported as well.

    hashtag
    Unread Count Syncing

    To enable the unread message count feature on the device, the user must start unread count syncing. This ensures that the user, as well as all channels and subchannels, have an up-to-date message unread count. To disable this feature, users simply stop the unread count syncing, which will stop updating the message unread count from their device.

    hashtag
    Start unread count syncing

    To start unread count syncing, you can use the following code:

    hashtag
    Stop unread count syncing

    To stop unread count syncing, you can use the following code:

    Get Channels

    SDK now supports querying channels based on provided channel IDs. The ChannelRepository class includes a getChannels method that takes an array of channel IDs as input and returns a live collection of channels. This live collection will contain all the channels that are being queried in the first page. This live collection will not support pagination.

    Any update to the channels present in this live collection will be automatically notified to the user. Furthermore,

    • This live collection will only contain valid channels. In case of invalid channels (such as user gets banned etc.) the list may exclude those channels.

    • If any channel id is invalid, live collection will throw error.

    circle-info

    💡 The maximum number of channel that can be queried is 100.

    Limitations:

    If the channel is not public and user leaves the channel, the channel will still remain in the live collection until user refresh or resets the live collection.

    Channel Unread Count

    hashtag
    Channel unread count

    The SDK provides a simple way for clients to retrieve the unread count for a channel. To view the unread count for a channel, we can get it from a channel object. This count represents the number of messages that you have not yet read in that channel.

    hashtag
    Check unread count support for channel

    To check if a channel supports the Unread Count feature, you can use the following code:

    hashtag
    Channel Mention Status

    To get the mention status of the current user in a channel, developers can use the following code.

    hashtag
    Subchannel Mention Status

    To get the mention status of the current user in a sub channel, developers can use the following code.

    iOS Push Notification Certificate Setup

    Process to setup iOS push notification certificates to receive notification from AmitySDK / AmityUIKit.

    In order to send or receive push notifications using our SDK, you would need to create push notification certificates from Apple Developer Console & Upload in our Amity console.

    Here are the steps to generate push notification certificate from Apple Developer Console.

    circle-info

    When a new .p12 certificate is created, previous certificate gets revoked and cannot be used again.

    Step 1:

    Install SDK for Ionic

    Use our Amity Social Cloud SDK with the Ionic Framework

    hashtag
    Ionic Framework

    We now support the Ionic framework in building your application using our web SDK. You can use our Chat natively to support your mobile or web applications built using the Ionic framework.

    Since Ionic is an HTML5 framework, it needs a native wrapper to access native SDK functionalities and run as a native app. We recommend using Capacitor.

    Capacitor will wrap your application in a native container so you can easily integrate our web SDK to run on iOS, Android, and web platforms.

    Live Objects/Collections

    Live Objects and Live Collections are observable data holders. The observer gets updated when there is a change of data in the local cache.

    There are two main sources that can make changes to the object and collection:

    • When an object gets updated by an action from the current device.

    • Real-time events of the subscribed objects from the server.

    Push Notifications

    Push notifications are small pop-up messages triggered by an application, even when the application is not open. Push notifications are an essential part of social features that a customer must provide to their end users.

    hashtag
    Webhook

    Clients who want to have the push notifications delivered to their own servers first in order to customise before it reaches their users, can opt for this method.

    In this solution, events are sent from Amity’s servers to the client’s servers via webhook. Clients can decide what to do with each events before it reaches the end user's device as notification. Clients have the ability to edit the notifications (i.e: translate the message), filter them (based on specific use case or user preferences), and perform analytics before sending them to the users. With this new feature, clients can also have notifications for web apps.

    Presence State

    hashtag
    Overview

    Presence state is a vital aspect of any modern application, acting as a driving factor for engagement products by showing the user's current availability. The AmitySDK supports both observing and notifying the presence of users, analogous to being online and observing users' online statuses.

    hashtag

    Android Push Notifications Initialization

    hashtag
    Initialize Push Notification

    FCM dependency:

    Before you can start receiving push notifications, you need to obtain a FCM unique token string that identifies each FCM client app instance:

    Update Channel

    hashtag
    Update a Channel

    The updateChannel function allows users to modify the properties of a channel. This function is useful in cases where a channel's details need to be updated, such as changing the channel's display name or avatar.

    The function takes a channelId parameter as a required input, which specifies the channel to be modified. Additionally, users can pass in any number of optional parameters to update the channel's properties. These optional parameters include:

    Flutter Live Objects/Collections

    hashtag
    Live Objects and Live Collection

    In Flutter SDK, we have a concept of Live Object and Live Collection. Live Object is represented by StreamSubscription<Object> instance and LiveCollection is represented by an instance of LiveCollection. LiveCollection is a generic class that encapsulates any other object and notifies the observer whenever any property of encapsulated object changes. Live Object helps to observe changes in a single object whereas Live Collection helps to observe changes in a list of objects. For example:

    Query Members

    hashtag
    Query Channel Members

    The ability to search for and query members within a chat channel is an essential feature for creating a seamless and engaging user experience. With Amity Chat SDK, developers can use the query member feature to allow users to search for and retrieve member information within a channel. We will discuss how to use the query member feature of Amity Chat SDK to enable users to search and retrieve member information within a chat channel.

    For the specified channel, the list of users will be sorted by as a lastCreated default parameter. Users can also choose to sort by lastCreated

    Message Delivery Status

    hashtag
    Mark Message as Delivered

    When you send a message to someone, it's important to know whether that message has been delivered to the recipient's device or not. This is where the "Mark message delivered" function comes in.

    By calling this function, you can update the status of a message to "delivered", which indicates that the message has been successfully delivered to the recipient's device. This can be useful for ensuring that important messages have been received by the intended recipient.

    The parameters for this function are:

    Custom Message

    hashtag
    Send a Custom Message

    If you'd like to display content on your app that cannot be represented by the available text, image, video, and file message types, you can create your own custom message type. Custom message type allows you to include the necessary data for rendering, such as additional metadata and custom data formatting. This is useful if you want to present specific types of content to your users.

    Here is a brief explanation of the function parameters:

    Register and Unregister Push Notifications on a Device

    hashtag
    Client Registration

    Registering your app for push notification will require a registered AmityClient instance (necessary to know which user is associated with this device) and a push notification token.

    Amity's Development Kit does not manage:

    Subchannel Unread Count

    The SDK provides a simple way for clients to retrieve the unread count for a sub channel. To view the unread count for a sub channel, we can get it from a sub channel object. This count represents the number of messages that you have not yet read in that sub channel.

    hashtag
    Check unread count support for sub channel

    Reply to a Message

    In addition to creating top-level messages, Amity Chat SDK also allows you to reply to existing messages. To reply to a message, you'll need to specify the parent message's parentMessageId as one of the parameters. This allows the SDK to associate the new message as a reply to the parent comment.

    Similar to creating a top-level message, you can use the SDK's optimistic creation feature to create a reply message.

    Version 6

    Version 5 (Maintained)

    Search Members

    hashtag
    Search Channel Members

    The searchMembers function in the AmityChannelParticipation class is used to search for members in a channel when mentioning. It takes the following parameters:

    The function returns a of ChannelMember

    Text Post

    Text posts are a simple yet powerful way to create and share text-based content with other users on our platform. With the Amity Social SDK, users can quickly and easily create text posts and add them to a user's or community's feed. As demonstrated in the code sample below, you can simply include the text data as a parameter when creating a text post.

    Here's an explanation of the method's parameters:

    • text: This is a required parameter of type String, which represents the text content of the new post. You can pass in any text you want to include in the post, up to a maximum length of 20,000 characters.

    Create Post

    Amity SDK provides developers with a powerful set of tools for creating a wide range of post types with support for a broad range of content formats, users can create highly dynamic and engaging posts that help to drive user engagement and increase retention, including:

    npm install @amityco/ts-sdk --save
    yarn add @amityco/ts-sdk

    For more information, go to Webhook Events settings.

    In this scenario, there's no SDK involvement needed. The whole notification process is managed on your end.

    hashtag
    Direct Push Notifications

    With this solution, the notifications will be triggered and delivered to your users directly by Amity's servers. There's nothing that the iOS client has to do in order to display the notification to your users. Amity's servers will prepare for you a notification that can be directly displayed to the user as and when it's received.

    Click for more Network Level settings.

    Click to learn on different SDK Settings.

    circle-info

    Direct push notifications only support on iOS, Android, and Flutter SDKs.

    hashtag
    Push Notification Examples

    As Amity's servers are responsible for choosing the content of the push notification, you can expect your users to receive the following notifications for different kinds of events:

    • Event: New channel has been created and the user has been added among other members. Push Notification Title: %s (%s = New Channel display name) Push Notification Body: You're now member of %s! (%s = New Channel display name)

    • Event: A new user has joined a channel. Push Notification Title: %s (%s = user display name) Push Notification Body: %1s has joined %2s (%1s = user display name, %2s = channel display name)

    • Event: A new message has been received in a channel where the user is already a member. Push Notification Title: %1s (%2s) (%1s = user display name, %2s = channel display name) Push Notification Body: %s (%s = message text body if text message, Image Message if image message, Special message otherwise)

    hashtag
    Push Notification Triggers

    A new push notification will be sent to a specific user when:

    • A new message is sent in a channel of the user who is already an existing member of it.

    • A new channel is created and the user is among the listed members of the channel on creation.

    • A new member joins a channel of the user who is already an existing member of it.

    Image Handling
    Video Handling

    File Post

  • Video Post

  • Live stream Post

  • Poll Post

  • Custom Post

  • We provide a method for creating each type of post. To create a post, you must first select the target type. The target type is either a user or a community.

    • User: If you wish to create a post on someone else's feed, provide their user ID as the targetId and set the target type to the user. If you want to create a post on your own feed, leave the target ID empty.

    • Community: To make a post on a specific community, set the target type to community and provide the community ID.

    Each post can have up to 20,000 characters, and custom posts should not have JSON data that is larger than 100KB.

    Text Post
    Image Post

    hashtag
    Getting Started

    We will walk you through the process of installing ionic and all the necessary dependencies for development.

    hashtag
    Installing Ionic

    Ionic comes with a convenient command line utility to start, build, and package Ionic apps. To install it, simply run:

    hashtag
    Adding Capacitor to your app

    In the root of your application, install Capacitor:

    hashtag
    Adding support for native platform

    Now, we need to copy the native platform template into your application:

    platform

    The platform template to add (e.g. android, ios).

    hashtag
    Opening the Application

    To open the application in your IDE, run:

    platform

    The platform you are using (e.g. android, ios).

    circle-info

    For Android, it will open Android Studio. For iOS, it will open Xcode.

    hashtag
    Where to go next

    Now you’re ready to start integrating our chat SDK into your application.

    hashtag
    Using our Chat SDK

    • Ionic with JavaScript framework

    sudo npm install -g @ionic/cli 
    npm install @capacitor/core --save
    ionic capacitor add <platform>
    npx cap open <platform>
    Safari: 9+
  • Opera: 25+

  • channel
    message
    community
    posts
    Dynamic Import with SSR disabledarrow-up-right
    herearrow-up-right
    When a user ID is created, it can be up to 50 characters in length.
  • If displayName is passed, but secured mode is enabled, the values will be ignored.

  • authToken : This is an optional parameter of type String that represents the user's authentication token. If provided, it will be used to authenticate the user when accessing the Amity application. For further information about security please visit the security page.

  • Go to Apple Developer Console (i.e https://developer.apple.comarrow-up-right) and click on Certificates.

    Step 2:

    Select Apple Push Notification Service SSL (Sandbox & Production)

    circle-info

    This certificate will be applicable for both Sandbox & Production environments so you do not need to create a separate for each one.

    Step 3:

    Follow the rest of the steps of creating certificates as shown by apple & download the .cer file.

    Step 4:

    Double click on .cer file you downloaded in the last step in Finder. After few seconds, Keychain Access program should open.

    Step 5:

    Select Login → My Certificates, then right click on the Apple Push Services certificate that you just installed. It would show you with some options as shown below.

    Step 6:

    Select Export “Apple Push Services …” option and save the file using .p12 extension. If you add a password while exporting, you will need to enter the same password in Amity Console.

    Step 7:

    Open Amity Console. Select Settings → Push Notifications & Upload this .p12 file to Amity Console.

    circle-info

    This certificate can be used to receive push notification in your production build (Distributed through Appstore or Testflight). Currently we do not support receiving push notification in Debug build.

    That’s it. Now the certificate is setup, Please follow the steps shown in Register & Unregister Push Notifications section to correctly send APNS token to receive push notification.

    circle-info

    Please make sure you have Push Notification capabilities enabled in your Xcode Project.

    For an in-depth explanation on how your SDK handles Live Objects and Live Collections, refer to the platform-specific subpages in this section.
    circle-info

    By subscribing to a specific topic in the Real-time event system, users can ensure that they are receiving the most up-to-date information and notifications related to the observed object across devices.

    hashtag
    Live Object

    Live Object allows users to observe the states of a single object within the app, such as a post, message, or channel. With Live Object, users can automatically receive notifications of any data updates related to the observed object, whether from the network or locally.

    Live Object also provides additional states, such as isLoading and error, which can be helpful for understanding the status of the observed object and any potential issues that may arise.

    Live Object API is designed around the observer design pattern, allowing users to subscribe to an object, receive notifications of any data updates, and unsubscribe when necessary. These updates are delivered via Snapshot, a captured state that is frozen and cannot be changed. Users can own and access these snapshots, using them to stay up-to-date with the latest data within the app.

    It's worth noting that while data updates may occur internally within the SDK, these updates will not affect previous snapshots. The only way for users to see the latest data is by getting new snapshots delivered via Live Object updates.

    hashtag
    Live Collection

    Live Collection allows users to observe changes to an entire collection of data within their app in real-time. Live Collection works similarly to Live Object, with the main difference being that Live Collection notifies changes related to the entire collection rather than just a single object.

    To use Live Collection, users can observe to changes on a specific collection within the SDK. The collection handler then receives a snapshot of changes since the last result, which includes three possible events:

    • the indices of the objects that were deleted

    • the indices of the objects that were inserted

    • the indices of the objects that were modified.

    By subscribing to changes on a specific collection using Live Collection, users can stay up-to-date with the latest changes and updates to important collections within the app. This can be particularly helpful for managing large amounts of data or monitoring changes to frequently updated collections, such as messages or posts.

    Presence Setting

    AmitySDK offers specific methods that allow the logged-in user to enable, disable, or query about presence settings. When these presence settings are enabled, the user is prepared to synchronize their presence state with the server.

    Users can enable or disable their presence state feature. Disabled users will be considered offline and cannot use any presence-related functionalities. Network-level settings can also affect this feature.

    circle-info

    Presence State feature is disabled by default at both the network and user levels. Please consult with Amity Team to enable this feature on the network level.

    hashtag
    Enable Presence Status

    The SDK user can invoke the enable() method within client.presence to activate their presence status.

    hashtag
    Disable Presence Status

    The SDK user can invoke the disable() method within client.presence to deactivate their presence status. When disabled, the user will be unable to sync both their own heartbeat and the presence of other users in the network. This action also halts any ongoing heartbeat synchronization processes.

    hashtag
    Query Presence Status

    The SDK user can invoke the isEnabled() method within client.presence to check their presence status. This method also determines if the presence state feature is available for the app. If unavailable, isEnabled() returns false. If the feature is available, the method checks the user-level settings, which are managed through the enable() and disable() methods as previously described.

    Retrieve the current FCM tokenarrow-up-right
  • Monitor FCM token generationarrow-up-right

  • You can initialize the services with the obtained token. Please note that the FCM token can be changed through application life cycle. Please make sure that the FCM token supplied to the messaging SDK is up to date. To notify the messaging SDK of the latest token, the following line of code can be called whenever necessary:

    hashtag
    Retrieve Push Notifications

    To retrieve push notifications, use a service that extends FirebaseMessagingService. Refer to Firebase's messages handlingarrow-up-right documentation for the detailed information.

    hashtag
    Push Notification In China

    Since Google play services are banned in China, The messaging SDK provides Baidu push services as a substitute for FCM. The messaging SDK requires an api key and a secret key from Baidu:

    https://push.baidu.com/arrow-up-right

    Baidu dependency:

    Note: Baidu push services require number of additional permissions. You can find a list of permissions herearrow-up-right.

    Baidu API key is needed for Baidu push services initialization:

    Note: The messaging SDK always consider FCM as a primary push provider and Baidu as a secondary push provider. If the messaging SDK detects Google play services on the device, Baidu push services won't be initialized.

    • displayName: The new display name for the channel.

    • avatarFileId: A new avatar image for the channel - Used to store ID of image file that represents avatar of the channel. To obtain file ID to set as channel avatar please see Upload Images section

    • tags: Arbitrary strings that can be used for define and query for the channels

    • metadata: Additional metadata to be associated with the channel.

    circle-info

    metadata is implemented with last writer wins semantics: multiple mutations by independent users to the metadata object will result in a single stored value. No locking, merging, or other coordination is performed across multiple writes on the data.

    Version 6

    Beta (v0.0.1)

    StreamSubscription<AmityPost>
    or
    LiveCollection<AmityMessage>
    .

    hashtag
    How it Works

    SDK handles lots of data received from various sources. Data can be present in local cache. It might also be queried from the server or received from some real-time events. What this means is that the same data is constantly updating. The data that you are accessing at the moment can get updated by other sources and becomes out of sync. Live Object and Live Collection help in syncing the data so you will always get the most recent one. Whenever the data updates, you will be notified through helper methods in Live Object and Live Collection classes.

    New data gets automatically collected everytime when there is an update and user need not refresh to get the recent data.

    hashtag
    LiveObject

    StreamSubscription<Object> is a native flutter class that keeps track of a single object. It is a live object. In Flutter AmitySDK, any object which provides Stream is a Live Object.

    Examples:

    This function help listen to Live Object. Whenever any property for the observed object changes, the listen callback will be triggered.

    hashtag
    Live Collection

    LiveCollection is a generic class that keeps track of a collection of objects. It is a Live Collection. In Flutter SDK, any object which is encapsulated by LiveCollection class is a live collection.

    Examples:

    • MessageLiveCollection

    • ChannelLiveCollection

    LiveCollection exposes these methods:

    • asStream

    • onError

    These methods help observe a Live Collection. Whenever any property for any object within the collection changes, the observer is triggered, as well as observing any errors from the collection.

    hashtag
    Stream Observer

    asStream method can get triggered multiple times throughout the lifetime of the application as long as its associated Stream<List<Object>> is retained in memory.

    asStream method will be called from the main thread so you can perform any UI update-related task within the listen block itself.

    • If the requested data collection is stored locally on the device, the block will be called immediately with the local version of the data.

    • In parallel, a request is made to the server to fetch the latest version of the data. Once the data is returned, the listen block will be triggered again.

    • Any future changes to the data from any sources can trigger in the listen block.

    hashtag
    Pagination

    AmityCollection in SDK returns a maximum of pageSize items per page. It has loadNext() method to fetch more data. It also exposes hasNext property to check if next page or previous page is present.

    Once next page is available, the same listen block gets triggered and you can access the collection as shown above. If you want to shrink the collection to the original first page, you can do so by calling reset() method on the same collection.

    One typical usage of LiveCollection is in ListView. Below is an example of fetching a collection and updating its state it in a Widget.

    or
    firstCreated
    .

    All participation related methods in a channel fall under a separate ChannelParticipation class.

    All participation related methods in a channel fall under a separate ChannelParticipation class.

    You can get a list of all members, or add memberships, roles , search parameters to get certain members of the channel.

    Version 6

    Beta (v0.0.1)

    hashtag

    • subchannelId: The ID of the subchannel where the message is located.

    • messageId: The ID of the message you want to mark as delivered.

    hashtag
    Get Message's Read Users

    In a chat application, it is often necessary to track which users have read a message. The Get Message's Read User function allows developers to retrieve a list of users who have read a particular message. This function can be useful for a variety of purposes, such as displaying read receipts or tracking user engagement with a particular message.

    To use this function, you can call the getMessageReadUsers method, this will return a collection of users who have read the message.

    hashtag
    Get Message's Delivered Users

    It is also important for users to know whether their messages have been successfully delivered to the intended recipients. The "Get message's delivered user" function allows users to query the list of users who have marked a particular message as delivered. This feature can be useful in scenarios where users need to know whether their messages have reached their intended recipients, such as in a customer service application or a team collaboration tool.

    The function takes a message ID as a parameter, and returns a collection of user objects who have marked the message as delivered. By observing the live collection, users can receive real-time updates as new users mark the message as delivered.

    data: A free-form JSON object that can be customized based on your use cases.

  • subchannelId: An identifier for the subchannel where the message will be sent. Subchannels are subdivisions within a channel that represent individual topics or chat threads. Messages and interactions occur within subchannels, not the main channel itself.

  • tags - Arbitrary strings that can be used for defining and querying for the messages.

  • Version 6

    Version 5 (Maintained)

    Version 6

    Version 5

    Version 6

    Beta (v0.0.1)

    user-facing requests for push notifications and authorizations

  • the creation and refreshing of push notification tokens

  • It's up to your app to take those steps and pass the notification token to the SDK.

    We recommend observing the completion block outcome to ensure a successful registration.

    If the device was previously registered with this or another user, the previous registration is invalidated as soon as this new request is received, which means that the device will always receive notifications of up to one user.

    hashtag
    Client Unregistration

    Unlike the registration, unregistering for push does not require the AmityClient instance to be associated with any user, therefore you can unregister the device from receiving push notifications as soon as the AmityClient has been initialized with a valid API key.

    hashtag
    The userId Parameter

    The unregistration allows to pass an optional userId:

    • if a valid userId is passed, Amity's backend will stop sending push notifications to this device only if the currently active push notification associated with this device is also associated with that user. No action is taken otherwise.

    • if no userId is passed, Amity's backend will stop sending push notifications to this device.

    You can register and unregister as many times as you'd like, however please remember that we use the "Last write wins" strategy.

    To check if a sub channel supports the Unread Count feature, you can use the following code:
    Version 6

    Version 5 (Maintained)

    Version 6

    Beta (v0.0.1)

    objects. You can filter search results with more than one option, such as filtering by muted and banned users. The role filter, which takes the role enum as an argument.

    If no keyword is supplied, the list of users will be organized alphabetically by display name. When a keyword is provided, the list will be arranged based on search rank.

    It takes the following parameters:

    • displayName/keywords: This parameter takes in the display name or user ID of the member being searched.

    • roles: This parameter is used to filter search results by roles:

      • member - Standard member

      • mute - Muted member

      • ban - Banned member

    Supported ✅ (please wait while we prepare a real example!)

    Live Collection

    targetType - Type of the target, either a particular community or a user feed.

  • metaData - Additional properties to support custom fields.

  • tags - Arbitrary strings that can be used for defining and querying for the posts.

  • Use AmityTextPostBuilder to create text post.

    Version 6

    Beta (v0.0.1)

    Get User Information

    In the Amity SDK, a user is represented by an AmityUser object, which contains the user's unique userId and displayName. The userId is an immutable value that is assigned to a user when their account is created, and cannot be changed afterwards. This value serves as a unique identifier for the user within the SDK, and is used to perform actions such as sending messages or creating connections between users.

    To retrieve an AmityUser object for a specific userId, you can use the getUser method provided by the UserRepository. This method accepts the userId as a parameter and returns a of AmityUser. The live object allows developers to observe changes to the user's properties in real-time, ensuring that their app remains up-to-date with the latest user information.

    Follow the below code to retrieve a user object:

    hashtag

    To retrieve multiple users, you can use getUserByIds method provided by UserRepository. This method accepts a collection of userId as a parameter and returns a ofAmityUser.

    The functionality isn't currently supported by this SDK.

    The functionality isn't currently supported by this SDK.

    The functionality isn't currently supported by this SDK.

    Flag / Unflag User

    Flag / Unflag User feature is an essential tool for maintaining a safe and engaging chat community. With Amity Social Cloud, you can use the flag and unflag user feature to allow moderators and administrators to monitor any inappropriate behavior within a chat channel.

    In this section, we will discuss how to use the flag and unflag user feature of Amity Chat SDK to maintain a safe and engaging chat community.

    To flag / unflag users on iOS, Android and Flutter SDK, create an instance of UserFlagger first:

    let userRepository: AmityUserRepository = AmityUserRepository(client: client)
    
    

    The UserFlagger lets you flag and unflag a user. It also exposes an asynchronous way to check whether the current logged-in user has already flagged the given user or not.

    hashtag
    Flag a User

    To flag a user, call the following method:

    hashtag
    Unflag a User

    To unflag a user, call the following method:

    hashtag
    Check Flagged By User

    To check whether a user has been flagged by the current user:

    Ban/Unban a List of Channel Members

    When a user is banned in a channel, they are removed from a channel and no longer able to participate or observe messages in that channel.

    Moderators can ban and unban users. When a user is banned in a channel, they are forcibly removed from the channel and may no longer participate or observe messages in that channel. All their previous messages in the channel will also be automatically deleted.

    A user that has been banned from a channel can not rejoin the channel until they have been unbanned.

    hashtag
    Global Ban

    As well as the banning and unbanning of users, admins also have the ability to global ban a user. When a user is globally banned, they can no longer access Amity's network and will be forcibly removed from all their existing channels. All the globally banned user's messages will also be deleted.

    The globally banned user can not access Amity's network again until they have been globally unbanned.

    circle-info

    When a user is banned, it can take up to 30 seconds before the user is disconnected from the network.

    hashtag
    Ban Users

    Banning members is a more heavy-handed moderation method. When a user is banned, all its messages are retroactively deleted, it will be removed from the channel, and it will not be allowed to join the channel again until he is explicitly unbanned.

    Version 6

    Beta (v0.0.1)

    hashtag
    Unban Users

    Supported ✅ (please wait while we prepare a real example!)

    Version 6

    Beta (v0.0.1)

    circle-info

    This feature does not work with Broadcast and Conversation channels. Calling banMembers() or unbanMembers() on these channels will result in an error.

    Video Message

    hashtag
    Send a Video Message

    Video messages allow users to share videos within a chat or social platform. This could be anything from a quick clip to a longer, more detailed video. With the Amity SDK, developers can easily integrate video message functionality into their apps, allowing users to record, upload, and share videos in real-time.

    To send a video message, you must pass a valid local file URL instance instead. You can also specify an optional caption as part of the message. This caption is accessible via the data property in the message model under the caption or text key. You can add up to 1,000 characters of text per message. When a video is uploaded, it is automatically resized to the maximum size of 480p.

    For further information regarding a video information please refer to page.

    circle-info
    • The maximum file size of the video is 1 GB.

    • The thumbnail for the video message is created automatically.

    Here is a brief explanation of the function parameters:

    • text/caption: A string that contains the text message that the user wants to send. This parameter is mandatory as it contains the actual message content.

    • attachment: The local video path that the user wants to send on the device

    Version 6

    Version 5 (Maintained)

    Version 6

    Version 5 (Maintained)

    Supported ✅ (please wait while we prepare a real example!)

    Channel Rate-Limiting

    This method is useful when there is a large number of messages going through the channel, which can make the message stream hard to follow. Setting a rate limit enables the SDK to queue up messages once the number of message in a specified window exceeds the defined limit, allowing a slower stream of messages to be published to the user at the expense of adding more latency (because newer messages will be sent to the queue first and not delivered until all previously queued messages are delivered).

    There is an internal limit of 1000 messages that can be queued by the rate limit service, if more than 1000 messages are queued up, the system may skip publishing the older messages in order to make room for newer messages. We believe this is the preferred behavior for users, as users will most likely want to see newer messages in a real-time conversation instead of waiting for a significant amount of time for old messages to be published to them first.

    Note that the SDK permanently stores all messages it receives in the system before the rate limit comes into effect: in the case of a large spike of incoming messages, even if a message did not get published to a user in real-time, that user can still scroll up to see message history and see that past message.

    The functionality isn't currently supported by this SDK.

    Supported ✅ (please wait while we prepare a real example!)

    The functionality isn't currently supported by this SDK.

    The above method enables a rate limit of 5 messages every 60 seconds: once there are more than 5 messages sent, from any user, within 60 seconds, those messages will be queued on the server and not published to other channel members until 60 seconds have passed. The rate limit will last as long as the period specified in the method call: in the example above the rate limit will be active for 10 minutes (600 seconds).

    If you would like to have a permanent rate limit, call the method above with a period of -1 seconds.

    In order to disable the rate limit, simply call removeRateLimitWithCompletion:

    The functionality isn't currently supported by this SDK.

    Supported ✅ (please wait while we prepare a real example!)

    The functionality isn't currently supported by this SDK.

    Image Post

    Prior to creating an image post, it is crucial to upload the images that will be included in the post data to ensure that the necessary information is accessible and can be linked to the post. This requires uploading the image first, to obtain the image data that will be used in creating the image post. To upload an image, please refer to Upload Images.

    Upon successful completion of the image upload process, you can include the image data as a parameter when creating an image post, as demonstrated in the code sample below.

    Here's an explanation of the method's parameters:

    • text: This is a required parameter of type String, which represents the text content of the new post. You can pass in any text you want to include in the post, up to a maximum length of 20,000 characters.

    • images: Which represents an array of images uploaded by the user on Android, iOS and Flutter and imageIds for Typescript and Javascript to include in the new post. You can pass up to 10 images in a post.

    • targetType - Type of the target, either a particular community or a user feed.

    • tags - Arbitrary strings that can be used for defining and querying for the posts.

    • metaData - Additional properties to support custom fields.

    We can build the post first by using AmityImagePostBuilder. Then use the createImagePost method in AmityPostRepository to create image post.

    We can build the post first by using AmityImagePostCreator.Builder. Then use the same createPost method in AmityPostRepository to create an image post.

    circle-info

    A post can have a maximum of ten images.

    Roles and Permission

    Amity uses roles and permissions to provide users the ability to fully customize moderation experience on the platform. To learn more about Amity SDKs default roles and permissions, refer to Roles & Permissions page.

    hashtag
    Roles

    Creator of the channel can add and remove the role of user via AmityChannelModeration.

    Supported ✅ (please wait while we prepare a real example!)

    Version 6

    Beta (v0.0.1)

    Supported ✅ (please wait while we prepare a real example!)

    circle-info
    1. The channel creator is automatically assigned as the channel moderator.

    2. The previous/last moderator is not allowed to leave a community and an error is displayed.

    hashtag
    Permission

    You can check your permission in channel by sending AmityPermission enums to AmityCoreClient.hasPermission(amityPermission).

    Supported ✅ (please wait while we prepare a real example!)

    Supported ✅ (please wait while we prepare a real example!)

    Supported ✅ (please wait while we prepare a real example!)

    Supported ✅ (please wait while we prepare a real example!)

    Mute/Unmute a List of Channel Members

    Moderators can mute and unmute users. When a user is muted, they cannot send messages in a channel. However, muted users will still be allowed to observe messages in a channel. The status of being muted is indefinite but is only applied at the channel level. The mute and unmute operations can be done viaChannel object.

    hashtag
    Muting Channel Members

    When a user is muted, they cannot send messages in a channel and all the messages sent by that user to that channel will be rejected. This method is useful for preventing certain members from sending inappropriate messages, but still allowing them to participate in the conversation in a read-only manner. The timeout property allows you to make the timeout temporary, or permanent until unset by passing in -1.

    Supported ✅ (please wait while we prepare a real example!)

    hashtag
    Unmuting Channel Members

    Supported ✅ (please wait while we prepare a real example!)

    circle-info

    This feature is not applicable in Broadcast and Conversation channel. Calling muteMembers() or unmuteMembers() on these channels will result in an error.

    Video Post

    Prior creating a video post, it is crucial to upload the videos that will be included in the post data to ensure that the necessary information is accessible and can be linked to the post. This requires uploading the video first, to obtain the video data that will be used in creating the video post. To upload a video, please refer to

    Upon successful completion of the video upload process, you can include the video data as a parameter when creating a video post, as demonstrated in the code sample below.

    Here's an explanation of the method's parameters:

    • text: This is a required parameter of type String, which represents the text content of the new post. You can pass in any text you want to include in the post, up to a maximum length of 20,000 characters.

    • videos: Which represents an array of videos uploaded by the user on Android, iOS and Flutter and videoIds for Typescript and Javascript to include in the new post. You can pass up to 10 videos in a post.

    • targetType - Type of the target, either a particular community or a user feed.

    • tags - Arbitrary strings that can be used for defining and querying for the posts.

    • metaData - Additional properties to support custom fields.

    Requirements for Video

    • Supported video types are 3gp, avi, f4v, flv, m4v, mov, mp4, ogv, 3g2

    We can build the post first by using AmityVideoPostBuilder. Then use the createVideoPost method in AmityPostRepository to create a video post.

    We can build the post first by using AmityFilePostCreator.Builder. Then use the same createPost method in AmityPostRepository to create an image post.

    circle-info
    • A post can have a maximum of ten videos.

    • Uploading HDR video format is not supported on iOS.

    File Post

    Prior to creating a file post, it is crucial to upload the files that will be included in the post data to ensure that the necessary information is accessible and can be linked to the post. This requires uploading the file first, to obtain the file data that will be used in creating the file post. To upload a file, please refer to

    Upon successful completion of the file upload process, you can include the file data as a parameter when creating a file post, as demonstrated in the code sample below.

    Here's an explanation of the method's parameters:

    • text: This is a required parameter of type String, which represents the text content of the new post. You can pass in any text you want to include in the post, up to a maximum length of 20,000 characters.

    • files: Which represents an array of files uploaded by the user on Android, iOS and Flutter and fileIds for Typescript and Javascript to include in the new post. You can pass up to 10 files in a post.

    • targetType - Type of the target, either a particular community or a user feed.

    • tags - Arbitrary strings that can be used for defining and querying for the posts.

    • metaData - Additional properties to support custom fields.

    We can build the post first by using AmityFilePostBuilder. Then use the createFilePost method in AmityPostRepository to create a file post.

    We can build the post first by using AmityFilePostCreator.Builder. Then use the same createPost method in AmityPostRepository to create an image post.

    circle-info

    A post can have a maximum of ten files.

    Image Handling

    The use of images as a visual representation of information is crucial in many software applications. Our SDK provides the tools and functionality needed to easily handle images. In this section, we will introduce you to image handling in Amity, including how to upload and retrieve images in the SDK.

    hashtag
    Image Data

    Property
    Description

    Search and Query Users

    hashtag
    Search User

    Query for users by their display name, receiving a collection of AmityUser matching your search. It requires two parameters: the display name you're searching for, and a 'sort option' from the AmityUserSortOption enum. If no keyword is supplied, the list of users will be organized alphabetically by display name.

    Users also have the option to sort by lastCreated

    Text Message

    hashtag
    Send a Text Message

    In a chat application, it's essential to send text messages to each other in real-time, allowing for quick and easy communication. Users can also view previous messages sent and received within the chat, allowing them to reference past conversations as needed.

    The sendTextMessage function is a feature provided by the Amity chat SDK that enables users to send plain text messages in a . This function requires two parameters: text

    Read Status & Unread Count (Legacy)

    For Android, iOS, JS SDK version 6.5.0 and below and TS SDK version v0.0.1-beta.42.3

    hashtag
    Reading Status and Unread Count

    The ChannelRepository object exposes a totalUnreadCount property that reflects the number of messages that the current user has yet to read. This count is the sum of all the unreadCount channels properties where the user is already a member.

    File Message

    hashtag
    Send a File Message

    A file message is a type of message that allows users to share files with each other within a chat or messaging app. This can include documents, images, videos, and other types of files. To send a file message, the user simply selects the file they want to share and sends it through the app.

    When a user receives a file message, they can view or download the file directly within the app. This makes it easy for users to share important files and collaborate with each other without having to switch between different applications or email clients.

    Join/Leave Channel

    hashtag
    Join a Channel

    The joinChannel function allows users to join a channel, making them a member of the channel. This function takes one parameter, channelId, which is the ID of the channel that the user wishes to join.

    Once the user joins the channel, they will be able to participate in conversations and receive updates about the channel's activity. It is important to note that this function is idempotent, which means that it can be called multiple times without causing any issues. If the user has already joined the channel, a successful result will still be returned.

    Query Channels

    hashtag
    Query Channels

    The getChannels function is a powerful function that allows you to search for and retrieve channels that match specific criteria. With this function, you can quickly and easily find the channels you need.

    The function accepts several parameters that allow you to customize your search. The keyword parameter is a string that specifies the search query, allowing you to search for channels based on their displayName

    Social

    iOS ​ Android ​ Web TypeScript React Native Flutter

    Amity Social SDK allows engineers to integrate social communities and user feed capabilities without the hassle of deploying and maintaining any server infrastructure. Companies can now build user-powered social news feeds and notifications into their mobile and web app in no time. Enabling you to engage your customers with the same tools used by many of the popular social applications.

    Let users create engaging content and engage with others through comments and reactions. Users can follow other users or topics and become members of various groups to get a personalized timeline of content.

    Activity feeds are also a great feature to directly engage with users. You can communicate with your users directly by posting important messages as announcements.

    npm install core-js
    import 'core-js/features/object/from-entries';
    import AmityClient from “@amityco/js-sdk”
    
    const amityClient = new AmityClient({ apiKey, apiEndpoint })
    amityClient.registerSession({ userId, displayName, avatarFileId })
    implementation 'com.github.AmityCo.Amity-Social-Cloud-SDK-Android:amity-push-fcm:x.y.z
    implementation 'com.github.AmityCo.Amity-Social-Cloud-SDK-Android:amity-push-baidu:x.y.z'
    await ChannelRepository.updateChannel({ 
        channelId: 'channelId', 
        displayName: channelName,
        avatarFileId: fileId,
        tags: ['tag1', 'tag2'],
        metadata: { hello: 'world' }
     })
    import { MessageRepository, MessageType } from '@amityco/js-sdk';
    
    const messageLiveObject = MessageRepository.createMessage({
      channelId: 'channel1',
      type: MessageType.Custom,
      data: {
        customField1: 'customValue1',
        customField2: 'customValue2',
      }
      tags: ['tag1', 'tag2'],
      mentionees: [{type: 'user', userIds: ['user1', 'user2']}],
    });
    Previous
    Audio Message
    Next
    Viewing Mesages
    // assume the client has been initialized with a valid API key
    // unregister from receiving push notifications for the user with id `userId`
    client.unregisterDeviceForPushNotification(forUserId: userId) { [weak self] _, success, error in
      ...
    }
    
    // unregister from receiving push notifications for this device
    client.unregisterDeviceForPushNotification(forUserId: nil) { [weak self] _, success, error in
      ...
    }
    
    import { MessageRepository } from '@amityco/js-sdk'
    ​
    const message = { ... };
    ​
    MessageRepository.createTextMessage({
      channelId: 'channelId',
      text: 'reply message',
      parentId: message.messageId
    });
    const liveChannel = ChannelRepository.getChannel('channel3');
    
    liveChannel.once('dataUpdated', data => {
      ...
    });
    repository.rateLimitPeriod(600, rateLimit: 5, rateLimitWindow: 60) { success, error in
      ...
    }
    repository.removeRateLimit { success, error in
      ...
    }
    repository.setRateLimit({
      period: 600,
      rateLimit: 5,
      rateLimitWindow: 60,
    }).catch(error => {
      ...
    });JavaScript
    repository.removeRateLimit().catch(error => {
      ...
    });
    hashtag
    Get Single User

    The User Repository provides a method to get a single user. It returns a LiveObject which you can observe.

    You can also use the code below to get one user:

    hashtag

    hashtag
    Get All Users

    The User Repository provides a method to get a list of all users, which will be returned as a LiveCollection:

    This method takes an optional sortBy parameter which must be a UserSortingMethod - these include displayName, firstCreated, and lastCreated:

    The functionality isn't currently supported by this SDK.

    Live Object
    Live Collection
    subchannelId
    : An identifier for the subchannel where the message will be sent. Subchannels are subdivisions within a channel that represent individual topics or chat threads. Messages and interactions occur within subchannels, not the main channel itself.
  • tags - Arbitrary strings that can be used for defining and querying for the messages.

  • circle-info

    Refer to Video Handling for sample code on how to upload videos and check its progress.

    Version 6

    Beta (v0.0.1)

    Video Handling
    An image post data structure is:
    circle-exclamation

    Updating image post in JS SDK is not yet supported.

    Version 6

    Beta (v0.0.1)

    circle-info
    • Updating images in image post is not yet supported.

    • Refer to Post target type for a more detailed explanation of the targetType parameter.

    The channel moderator can promote a user/member to moderator.
  • The channel moderator can demote a moderator to a user/member.

  • This applies only to Live and Community channels’. This does not apply to Conversation Channel.

    await ChannelRepository.addRole({ 
      channelId: 'channel1', 
      userIds: ['user1'],
      role: 'role1',
    );
    ​
    await ChannelRepository.removeRole({ 
      channelId: 'channel1', 
      userIds: ['user1'],
      role: 'role1',
    );
    ,
    wmv
    ,
    vob
    ,
    webm
    ,
    mkv
  • The maximum file size of the video is 1 GB

  • The maximum duration of the video is 2 hours

  • Version 6

    Beta

    Version 6

    Beta

    circle-info

    Refer to Post target type for a more detailed explanation of the targetType parameter.

    circle-info
    • Updating files in a file post is not yet supported.

    • Refer to Post target type for a more detailed explanation of the targetType parameter.

    let userToBeFlaggedObject: AmityObject<AmityUser> = userRepository.user(forId: "badUser")
    guard let userToBeFlagged: AmityUser = userToBeFlaggedObject.object else { return }
    let userFlagger = AmityUserFlagger(client: client, userId: IdOfuserToBeFlagged)

    fileId

    Identifier for the uploaded file

    fileUrl

    The HTTP web URL for the uploaded file. You can use this fileUrl for downloading the image file.

    attributes

    Contains a dictionary with values for name, extension, size & mimeType

    of uploaded image

    metadata

    Contains additional metadata dictionary related to uploaded image such as height, width, isFullImage etc.

    hashtag
    Upload Images

    To upload an image to the system, you can use the Amity Image Upload API provided by the SDK. The API allows you to upload an image to the Amity server/ The SDK simplifies the process of uploading images by providing pre-built components that you can easily integrate into your application.

    Supported ✅ (please wait while we prepare a real example!)

    circle-info

    Supported image formats are JPG, PNG and cannot exceed 1GB in size.

    hashtag
    Retrieve Images

    You can retrieve an image from Amity using the Amity Image Retrieval API provided by the SDK. The API enables you to retrieve an image from the Amity server by supplying the image URL. Once an image is uploaded to the server, the image will be automatically transformed into four different sizes for versatile usage. We provided an option to retrieve a specific image size which are:

    • Small: is used for image thumbnails, with a maximum image size of 160 pixels per dimension. For example, this should be used for small previews in an image gallery that displays a large number of images in a grid.

    • Medium: is used for standard image display, with a maximum image size of 600 pixels per dimension.

    • Large: is used for full-screen image display, with a maximum image size of 1500 pixels per dimension.

    Supported ✅ (please wait while we prepare a real example!)

    Supported ✅ (please wait while we prepare a real example!)

    ,
    firstCreated
    , or
    displayName
    . When a keyword is provided, the list will be arranged based on search rank. The
    displayName
    sort option will be specified by default if it isn't specified.

    If the collection is sorted by displayName, the results will be alphabetically and case-sensitively ordered (aA-zZ). For example: adam, arthur, Alice, Andre, charlie, Kristen.

    Note: If the user ID or display name you’re searching for contains special characters, you’ll need to enter the whole keyword in order for it to appear in the search results.

    The code above will provide you with the list of users which matches with display name "Brian".

    The above example searches for all users whose display names start with "Test User 1".

    The queryUsers provides a way to search for users by their display name.

    hashtag
    Query Users

    Query for users to receive a collection of AmityUser based on a single parameter: a 'sort option' from the AmityUserSortOption enum. Sort the list by options such as displayName, firstCreated, or lastCreated. The displayName sort option will be specified by default if it isn't specified.

    hashtag

    If you wish to observe for changes to a collection of users, you can use liveUsers

    and
    subchannelId
    .

    Here is a brief explanation of the function parameters:

    • text: A string that contains the text message that the user wants to send. This parameter is mandatory as it contains the actual message content.

    • subchannelId: An identifier for the subchannel where the message will be sent. Subchannels are subdivisions within a channel that represent individual topics or chat threads. Messages and interactions occur within subchannels, not the main channel itself.

    • metaData: Additional properties to support custom fields.

    • tags - Arbitrary strings that can be used for defining and querying for the messages.

    Version 6

    Version 5 (Maintained)

    Version 6

    Version 5 (Maintained)

    When creating a message, we can also pass the parentId to make it appear under a parent.

    Version 6

    Beta (v0.0.1)

    circle-exclamation

    The limit for sending text messages is 10,000 characters per text message. Messages exceeding that limit will return an error and will not be sent.

    Subchannel

    Version 6

    The ChannelRepository provides getTotalDefaultSubChannelUnreadCount() method.

    hashtag
    Version 5 (Maintained)

    The ChannelRepository provides getTotalUnreadCount() method. It's giving the flowable of the number of messages that the current user has yet to read. This count is the sum of all the unreadCount channels properties where the user is a member of.

    hashtag
    Unread Mention

    To check whether the current user has been mentioned on one of the unread messages:

    hashtag
    Version 6

    hashtag
    Version 5 (Maintained)

    Version 6

    The Channel object exposes a unreadCount property that reflects the number of messages that the current user has yet to read. This count is the sum of all the unreadCount channels properties where the user is already a member. It also provides hasMention which is a boolean presenting having a mention for current user in channel.

    The startReading() and stopReading() methods let the server know that the current user is reading a channel. After the startReading()and stopReading() methods are called, the unreadCount is reset to 0.

    You can call both methods as much you'd like, the SDK takes care of multi-device management: therefore a user can read multiple channels, from one or multiple devices at the same time. In case of an abrupt disconnection (whether because the app was killed, or the internet went down, etc.), the SDK backend will automatically call the stopReading on the user's behalf.

    hashtag
    Version 6

    hashtag
    Version 5 (Maintained)

    Beta (v0.0.1)

    This is the legacy feature, for version 6.0.0 and above, please visit .

    A File message can include any of the following:
    • Image

    • Audio

    • File

    • Custom

    To send a file message, you must provide a valid local file URL instance of the selected file and file name for the file. The default file name is file. The SDK will check the size of the data whether it is exceeding the limit or not before sending it to the server. If the size of the data is more than the limit, the callback will return an Error object with the error information that you can parse and then show an error message.

    Here is a brief explanation of the function parameters:

    • text/caption: A string that contains the text message that the user wants to send. This parameter is mandatory as it contains the actual message content.

    • attachment: The local file path that the user wants to send on the device

    • subchannelId: An identifier for the subchannel where the message will be sent. Subchannels are subdivisions within a channel that represent individual topics or chat threads. Messages and interactions occur within subchannels, not the main channel itself.

    • tags - Arbitrary strings that can be used for defining and querying for the messages.

    Version 6

    Version 5 (Maintained)

    Here's a small example on how to create a message with an image attached. The process is pretty simple:

    1. Upload a file.

    2. Create a message with the uploaded file ID.

    circle-info

    Refer to for the sample code on how to upload a file to get fileId.

    Here's a small example on how to create a message with an image attached. The process is pretty simple:

    1. Upload a file.

    2. Create a message with the uploaded file ID.

    circle-info

    Version 6

    Beta (v0.0.1)

    hashtag
    Leave a Channel

    The leaveChannel function is used to disengage a user from a channel by removing them from the list of members. This function takes the channelId parameter, which specifies the ID of the channel that the user wishes to leave. Once the user has left the channel, they will no longer receive any messages or updates from the channel.

    Version 6

    Beta (v0.0.1)

    hashtag
    Channel Membership

    When a user joins a channel, they are able to observe and chat with other users in that channel. They are also automatically considered a member of that channel. The Chat SDK provides the ability to view which users are currently in the channel as well as invite other users to join the channel.

    Each channel is identified by a unique channelId, which is any string that uniquely identifies the channel and is immutable through its lifetime. When creating channels, you can specify your own channelId, or leave it to Amity's Chat SDK to automatically generate one for you.

    It's important to note that, createChannel guarantees that the requested channel is a new channel (except for conversation type), whereas joinChannel will attempt to join an existing channel. If there is a requirement to create a new channel, then use of createChannel then call joinChannel. Lastly calling getChannel only gives you back the channel LiveObject, but it won't make the current user join said channel.

    hashtag
    Observe for changes in Membership

    You can observe the channel to determine changes in the membership status. If the user is banned from the channel, you would want to show the particular UI and move from the chat screen.

    For example, in the event of a channel-ban, it's possible to implement the appropriate user interface, navigating the user to be redirected away from the chat screen.

    Supported ✅ (please wait while we prepare a real example!)

    Supported ✅ (please wait while we prepare a real example!)

    .

    Once you have made your query, the function returns a Live Collection of channels that match your query criteria. You can use this collection to display the search results in your app, or to further filter the results as needed.

    You can query channels with the following criteria:

    • keyword: Specify keyword that should be in channel displayName

    • includeDeleted : Specify whether to search for channels that has been closed. Possible values are:

      • null (default) - Show both channel is active and closed.

      • false - Search for channels that is still open

    • tags : Search for channels with the specific tags. If more than 1 tags are specified in the query, system will search for channels that contain any of those tags.

    • excludeTags : Search for channels without the specific tags. If more than 1 tags are specified in the query, system will search for channels that does not contain any one of those tags.

    • filter : Membership status of the user. Possible values are:

      • all (default) - Search for channels

      • member

    • types : type of channel to search for - conversation , broadcast , live or community

    • userId : Search for channels that is created by a given User ID

    circle-info

    If you use a UITableView or UICollectionView to display channel list data, the ideal location to reload table data is directly in the observe block of the live collection that you are displaying.

    Version 6

    Beta(v0.0.1)

    Amity social SDK allows you to:

    • Connect users through formation of communities

    • Boost user engagement by user-generated posts/comments in communities

    • Personalize the feed based on user’s membership to different groups and communities

    • React to user-generated content with our reaction tools

    • Enable comments on posts within your application, seamlessly

    • Support multiple messaging formats when posting content

    • Manage & moderate communities and users in admin panel

    • Filter out content that includes profanity using our auto-block tools

    • Assign roles and permissions on a role-based system

    hashtag
    Features

    hashtag
    Communities

    This page will guide you through the steps you need to take to integrate communities into your applications.

    hashtag
    Posts

    Here's an overview of posts and how you can get started with integrating them into your applications.

    hashtag
    Comments

    Here's an overview of how you can get started integrating comments into your applications‌.

    hashtag
    Reactions

    Let users react to messages, posts, and comments, which are visible to others.

    hashtag
    Feed & Timeline

    Let your users showcase their unique personalities right in their timelines‌.

    hashtag
    Follow/Unfollow

    Lets you create a relationship between your users in social features.

    arrow-up-right
    arrow-up-right
    arrow-up-right
    
    let moderation = AmityChannelModeration(client: <amityclient>, channel: <channel-id>)
    ​
    moderation.banMembers(["user1"]) { success, errror in
      ...
    }

    Mentions

    Mentions allow users to tag other users in messages, comments, and posts. It's a powerful tool for fostering engagement and collaboration within your social application. With mentions, users can easily direct messages to specific individuals or groups and can alert them to new content or important updates. In the SDK, mentions can be implemented in a range of ways, depending on your application's needs and user experience. Here are the models that support mentions creation and highlighting:

    • Mention in Post

    you have the flexibility to define your own mention data structure for representing mentions. This allows you to highlight mentioned text in a way that best suits the needs of your application and users. The most important aspect of mentions is to notify users when they have been mentioned, regardless of the specific data structure used. This ensures that users are able to quickly and easily engage with the content that is most relevant to them.

    hashtag
    Mention Users

    Upon creating a model above (a post, comment, or message) with a mention, you can include a JSON object in the metadata parameter. The metadata represents the mention object, which depends on the design of your data structure. However, Amity provides a default structure to help you create the mention metadata.

    To ensure prompt notification of the person mentioned, it's important to provide the list of user IDs for the mention users parameter. This will help ensure that the mentioned users are notified and able to engage with the content.

    • mentionUsers(userIds) - In order to mention users and notify specific users. This function supports all mentionable models.

    • mentionChannel(channelId) - In order to mention and notify the whole channel. This function supports only a message model.

    hashtag
    Default Mention Metdata Structure

    To represent mentions using our structure, you will need to utilize the AmityMention object. This object can be created during mentionable model creation, as well as during rendering. The model contains of four properties:

    • type - type of the mention - the possible types are user and channel, for post and comment only support mentioning user but message supports mention channel additionally.

    • index - start index of current mention

    circle-info

    The length property doesn’t include the “@“ mention sign. For example, “@all” mention’s length is 3.

    hashtag
    Mention Users Example

    Below is an example to create a comment with mentions by using our default mention metadata structure:

    circle-info

    We do not allow banned users to be mentioned, as we take a firm stance against harmful or inappropriate content in social applications. However, admins may still be able to access the names of banned users through the search users function. Once a message is sent, however, banned users' information will be excluded from the payload. Banned users will also not be notified or receive any push notifications if they are mentioned, further ensuring that they do not engage with the content.

    hashtag
    Render Mentions

    As we mentioned that we provided the flexibility for you to define your own mention object data structure to represent mentions. You can use the default data structure provided by the SDK to render mentions in your application, which can be accessed through the helper class. This allows you easily retrieve mentions and render them. The mentionable model contains properties related to the mention feature:

    • mentionUsers - The AmityUser object array contains details about users mentioned in the current content.

    • metadata - a flexible JSON object which can accommodate any information regarding the mentioned users. Our predefined structure for representing mentions is also in the metadata property.

    Below is an example to render mentions in a comment by using our default mention data structure:

    The following example demonstrate how AmityMentionMapper and AmityMention works in a comment. The function getAttributedString uses AmityMentionMapper to extract AmityMention from metadata, and return the highlighted text.

    There is no restrictions over how you'll handle the highlighting the mentions in your UI. At Amity, we pass this metadata property inside CommentRepository.createTextcomment

    hashtag
    Mention Notifications

    When users are being mentioned, they will receive push notifications. You can customize the push notification content such as the title and the body using the . Providing the notification title and body in the titleTemplate and bodyTemplate parameters respectively. Here is a sample model:

    User Presence

    The SDK also offers functionality to query and synchronize the presence of other users, enabling the creation of a UI that displays their online status. For example, you might use a green dot to indicate whether a particular user is online or offline.

    Within the SDK, a user's presence is represented by the AmityUserPresence object, which contains three properties.

    Property
    Remarks

    userId

    hashtag
    Query User Presence

    The SDK enables users to query the presence state for a list of users, with a maximum limit of 220. The getUserPresence method from the AmityUserPresenceRepository class can be used to fetch a list of AmityUserPresence objects.

    hashtag
    Sync & Unsync User Presence

    In addition to querying user presence, the SDK also offers a method to periodically sync the presence of other users. This functionality keeps users informed about the online status of others. One application of this feature would be to display a list of users and provide an online indicator for those who are currently online.

    hashtag
    Sync User Presence

    The SDK includes the syncUserPresence(id, viewId) method in the AmityUserPresenceRepository class to synchronize the presence of another user. This method adds the specified ID to the list of user IDs for presence synchronization, occurring periodically at set intervals. To observe the results of this process, use the getSyncingUserPresence() method. When presence information is obtained for the currently syncing user IDs, notifications are sent through the observer returned from the getSyncingUserPresence() method. For further details on observing presence, refer to the section.

    For optimal use, particularly when displaying a list of users, call this method as a list item appears to synchronize the user's presence state. Conversely, utilize the unsyncUserPresence(id, viewId) method to stop synchronization when a list item is no longer visible, ensuring that the maximum sync limit is never reached.

    circle-info

    The maximum number of user IDs that can be synced at a time is 20. If the count exceeds this limit, the SDK will log an error message to the console. To remove a user ID from the list, use the unsyncUserPresence(id:viewId:) method.

    This syncUserPresence(id, viewId) method also provides an optional viewId parameter. viewId is the unique id of the view that this user id is tied to. In most of the cases, you do not need to specify any value to this parameter. viewId is useful if you want to bind same user id to multiple views in same screen. In that case, if you want to unsync presence for one view, it won't affect presence syncing for same user id in another view.

    circle-info

    SDK will log a message in console incase of any error which occurs during syncing process.

    hashtag
    Unsync User Presence

    The SDK includes the unsyncUserPresence(id, viewId) method to cease syncing the presence of a specific user ID. When a user ID is unsynced, the SDK removes it from the current list of synced IDs, and the observer returned from the getSyncingUserPresence() method will no longer provide presence information for that user. The method also features an optional viewId parameter, functioning similarly to the syncUserPresence(id, viewId) method.

    The SDK also provides a convenient method to unsync all user ids which are currently being synced. This is particularly useful when you don’t care about the user ids being synced. One usecase for this is when user navigates to another screen which do not care about syncing previously synced users at all. So you can call unsyncAllUserPresence() method when the previous screen disappears.

    hashtag
    Observe User Presence

    After adding users for synchronization, the next step involves observing their presence. The SDK offers an observer via the getSyncingUserPresence() method. Whenever presence information is retrieved for users synced through syncUserPresence(id, viewId), this information is published through the observer.

    Accessing User Presence:

    You can access the presence information for synced users in two ways:

    1. Through the Observer Returned from getSyncingUserPresence(): When the presence information is updated, the observer provides an array of [AmityUserPresence] for the user IDs being synced. Users need to map AmityUserPresence from this array to the view where the information is to be displayed.

    2. Through the AmityUser Object: When presence information is fetched from the server, the

    hashtag
    Online Users Count

    The SDK provides the getOnlineUsersCount method in the AmityUserPresenceRepository class to query the count of online users. Please note that this count does not update automatically.

    hashtag
    Online Users Snapshot

    The SDK provides a method getOnlineUsersSnapshot in AmityUserPresenceRepository to query list of online users in a network. The list of users can be accessed through users property which returns an array of AmityUser.

    circle-info

    This snapshot is not auto updating & supports query of up to 1000 online users.

    When this snapshot object is initialized, it fetches the snapshot of user presences of all online users in current network. Then it maps those information to AmityUser per page and provides list of AmityUser with pagination. Each page can contain max 20 users. When snapshot is returned, it will contains users for first page. You can still fetch more users if available through loadMore() method. Once more users are fetched, user can access those users through users property. You can also use canLoadMore property to determine if there are more online users which can be fetched.

    Channel Presence

    The SDK also provides a way to query & sync presence of members of conversation channel. This allows you to create a UI which displays presence status of other members in the conversation channel. Example: A green dot to indicate whether other user is online or offline in conversation channel.

    In SDK, channel presence is represented by AmityChannelPresence object. This object contains 3 properties.

    Property
    Remarks

    channelId

    hashtag
    Sync & Unsync Channel Presence

    The SDK also offers the functionality to query and synchronize the presence of members within a conversation channel. This enables the creation of a user interface that displays the presence status of other members in the channel, such as using a green dot to indicate whether a user is online or offline within a specific conversation. In the SDK, channel presence is represented by the AmityChannelPresence object, which contains three properties.

    hashtag
    Sync Channel Presence

    The SDK includes the syncChannelPresence(id,viewId) method in the AmityChannelPresenceRepository class to synchronize the presence of members within a conversation channel. This method adds the specified ID to the list of channel IDs whose members' presence will be synced, and this process occurs periodically at a predetermined interval. To observe the results of this syncing process, use the getSyncingChannelPresence() method. When the presence information for the currently syncing channel members is obtained, it is published through the observer returned by the getSyncingChannelPresence() method. More details can be found in the section.

    When displaying a list of conversation channels, it is advisable to use this method. The observer offers a class named AmityChannelPresence that holds the presence information for the channel's members. Likewise, the unsyncChannelPresence(id, viewId) method should be used to stop syncing the presence state when a list item is no longer visible, ensuring that the maximum sync limit is never reached.

    circle-info

    Only syncing of Conversation channel type is supported ! The maximum number of channel IDs that can be synced at a time is 20. If the count exceeds this limit, the SDK will log an error message to the console. To remove a channel ID from the list, use the unsyncChannelPresence(id, viewId) method.

    This syncChannelPresence(id, viewId) method also provides an optional viewId parameter. viewId is the unique id of the view that this user id is tied to. In most of the cases, you do not need to specify any value to this parameter. viewId is useful if you want to bind same channel id to multiple views in same screen. In that case, When you unsync channel presence in one view, it won't affect presence syncing for same channel id in another view.

    circle-info

    SDK will log a message in console incase of any error which occurs during syncing process.

    hashtag
    Unsync Channel Presence

    The SDK offers the unsyncChannelPresence(id, viewId) method to cease syncing the presence of a particular conversation channel. If the channel ID is unsynced, the SDK will remove it from the list of channel IDs whose members are currently being synced. Consequently, the observer returned by the getSyncingChannelPresence() method will no longer contain information about this channel. This method includes an optional viewId parameter and operates similarly to the syncChannelPresence(id, viewId) method.

    The SDK includes a convenient method, unsyncAllChannelPresence(), to stop syncing all channels that are currently being monitored. This feature is particularly useful when the application no longer requires information about the channels being synced. For example, this method can be called when a user navigates to a different screen that has no dependence on the previously synced channels, allowing for an efficient transition between different parts of the application.

    hashtag
    Observe Channel Presence

    After adding the channels to sync, the next step is observing the user presence. The SDK provides an observer through the getSyncingChannelPresence() method. Whenever presence information is fetched for channels synced through the syncChannelPresence(id, viewId) method, that information is published through this observer.

    Accessing Channel Presence:

    • Through the observer returned from getSyncingChannelPresence()

    Whenever presence information is updated, the observer will provide an array of [AmityChannelPresence] for the channels that are being synced. Users must map AmityChannelPresence from this array to the view where this information is to be displayed

    Android Live Objects/Collections

    Live Objects are supported in the Android SDK with RxJava Data Streaming

    The RxJava3arrow-up-right library is being used in Android development to achieve Live Object and Live Collection behavior.

    It is a Java VM implementation of ReactiveX, a library for composing asynchronous and event-based programs by using observable sequences. The building blocks of RxJava are Observables and Subscribers. Observable is used for emitting items and Subscriber is used for consuming those items.

    You can visit ReactiveXarrow-up-right for more information.

    hashtag
    How it Works

    SDK handles lots of data received from various sources. Data can be present in local cache. It might also be queried from the server or received from some real-time events. What this means is that same data is constantly updating. The data that you are accessing at the moment can get updated by other sources and becomes out of sync.

    Rx3 Data Stream helps in syncing the data so you will always get the most recent one. Whenever the data updates, you will be notified through Flowable Objects and Flowable Collection.

    New data gets automatically collected everytime when there is an updation and user need not refresh to get the recent data.

    Live Collection is available for the following functionalities in user/community feeds via APIs:

    circle-info

    For any specific errors that's handled in PagingData please visit the web page below to properly handle its errors

    • Post Collection

    • Comment Collection

    • Reactions Collection

    hashtag
    How to Retrieve Data from Rx3 Data Stream

    To retrieve data from the RxStream, we need to subscribe to the Stream(Flowable/Single/Completable) by defining subscribing and observing threads.

    hashtag
    Events a Data Stream can Emit

    In the RxJava3 framework we have these different types of objects that can be observed:

    1. Flowable - emits a stream of elements

      • doOnNext

      • doOnError

    hashtag
    Data Stream Interface

    Data Stream uses all standard .

    hashtag
    Example

    To get channel data, below is a sample code.

    hashtag
    Kotlin's Coroutines bridge

    The Amity Android SDK comes equipped with asynchronous and data stream capabilities, powered by RxJava3 by default. However, for those who prefer to use Kotlin's Coroutines, the SDK can be seamlessly integrated with the following Kotlin extension functions, allowing for easy interoperability between Amity Android SDK functions and Kotlin Coroutines functions.

    hashtag
    Suspend functions

    By using the .await() method, it enables the conversion of Completable and Single<T> functions of the Amity Android SDK into suspend functions.

    hashtag
    Flow functions

    By using the .asFlow() method, it enables the conversion of Flowable<T> functions of the Amity Android SDK into Flow functions.

    hashtag
    Jetpack Compose compatibility

    Amity Android SDK seamlessly integrates with Jetpack Compose UI, allowing you to take full advantage of the modern UI toolkit provided by Jetpack Compose. You can effortlessly incorporate our SDK into your Jetpack Compose-based projects to enhance your app's social experience. This compatibility ensures that you can leverage the power of Jetpack Compose while benefiting from the features and capabilities our SDK provides.

    hashtag
    Flow of PagingData in Compose

    In Jetpack Compose, integrating data from a `Flow<PagingData<T>>` source into your UI is made easy through the `collectAsLazyPagingItems()` function. This function allows you to seamlessly paginate and display items within your Composable functions.

    To start using it, add compose paging dependency in your project app level build.gradle file.

    Then in your Composable functions, you can collect from flow and display data, and also can observe the load state.

    hashtag
    Flow in Compose

    By using collectAsState() method, it can deliver asynchronous data updates to your Compose UI components.

    Message Preview

    Messages preview is partial data of the message that offers a brief summary of incoming messages through channel and subchannel objects. It allows users to quickly assess partial message content without opening the entire message.

    circle-exclamation

    Message Preview is an on demand feature. Please submit your request to Amity Help Centerarrow-up-right to enable this feature. It will take approximately 5 business days to process your request.

    hashtag
    Message Previews in Applications

    Message previews play a crucial role in enhancing user experience in messaging platforms. By offering a brief glimpse of incoming messages through channel and subchannel objects, users can assess the urgency, context, and relevance of messages without needing to open the entire conversation. This feature is particularly beneficial in various scenarios:

    1. Notifications: When a user receives a push notification or a message alert, a message preview can be shown, allowing the user to decide whether to engage immediately or defer it to a later time.

    2. Chat List: In a list of ongoing conversations, each chat item can display the latest message as a preview. This helps users quickly identify and prioritize which chat to respond to first.

    3. Data Economy: In scenarios where users have limited bandwidth or are on metered connections, previews allow them to decide if they want to download or load the complete message or any associated media.

    Integrating message previews into applications can significantly boost user engagement and satisfaction. By offering users an efficient way to manage their interactions, apps can optimize response times and streamline communication workflows.

    hashtag
    Message Preview attributes

    Name
    Data Type
    Description
    Attributes

    hashtag
    Channel message preview

    Within our SDK, clients can effortlessly obtain message previews using a channel object attribute.

    hashtag
    Subchannel message preview

    Our SDK offers clients a straightforward approach to access message previews for subchannels through dedicated subchannel object attributes.

    Message Reaction

    Interactions are more fun when you can express yourself! Let users react using emojis, stickers, or thumbs up to messages.

    The Social SDK product also provides functionality for adding and removing reactions on messages. Users can add any number of reactions to a particular message, allowing them to engage with the content in a more expressive and nuanced way. Additionally, users can also remove reactions that they have added to a message, providing greater control and flexibility over their engagement with the content.

    hashtag
    Add Reaction

    The addReaction function allows users to add a reaction to a message. The function takes the name of the reaction as a parameter, with a maximum length of 100 characters. The reaction name is case-sensitive, which means that "like" and "Like" are treated as two different reactions.

    You can add reactions to a given through the addReaction method.

    • referenecId - ID of the message.

    • reactionName - name of the reaction that you will remove. Reaction name is case sensitive, i.e "like" & "Like" are two different reactions.

    hashtag

    Version 6

    Beta

    hashtag
    Remove Reaction

    Similarly, the removeReaction function allows users to remove a previously added reaction from a . This provides users with greater control over their engagement with the content and allows them to change their mind or update their reaction to the message over time.

    You can remove a reaction from a reference by calling removeReaction.

    • reactionName - name of the reaction that you will remove. Reaction name is case sensitive, i.e "like" & "Like" are two different reactions.

    • referenecId - ID of the message.

    Version 6

    Beta (v0.0.1)

    hashtag
    Reaction Query

    To further facilitate the management of reactions in your app, the Chat SDK product includes a getReactions method that allows you to retrieve information about a specific reaction or all reactions on a message.

    Using this method, you can fetch detailed information about a particular reaction, including the user who made the reaction, the timestamp of the reaction, and any additional metadata associated with the reaction. This can be useful for analyzing the sentiment of the community and gaining insights into the types of content that are resonating with your users.

    To query getReactions you'll need to simply provide referenceType and referenceId to query specific type of reactions. For further information regarding reaction reference types, please see - .

    Supported ✅ (please wait while we prepare a real example!)

    Version 6 and Beta(v0.0.1)

    Edit and Delete Messages

    AmityMessageRepository class provides APIs for you to perform actions on messages you've sent or received. These actions include editing and deleting an existing message, as well as marking a message as being read by you. You can only perform edit and delete operations on messages you've sent.

    hashtag
    Edit Messages

    You can only perform edit and delete operations on your own messages. When editing a message, the message's editedAtDate will be set to the current time. This allows you to provide UI to the user to inform the user of specific messages that have been edited, if needed. An optional completion block can be provided to notify you of operation success.

    Currently, the Chat SDK has only 2 editable data types, TEXT and CUSTOM

    To edit the message, you need to pass the following parameters:

    • messageId

    hashtag
    Delete Messages

    The delete message functionality allows users to remove a message from a chat or messaging application. This feature provides flexibility and control, allowing users to delete messages they no longer wish to be visible to other participants in the conversation.

    By utilizing the delete message function, users can remove a specific message from the chat history. This can be useful in various scenarios, such as correcting mistakes, removing sensitive or inappropriate content, or simply managing the flow of the conversation. Once the message is deleted, it may still be shown as a deleted message with timestamp which depends on the condition.

    The delete message function typically requires the messageId as a parameter, which uniquely identifies the message to be deleted. Once the message is deleted, it will no longer be visible to other users in the chat or messaging context.

    For deleting a message, you need to pass the ID of the message to delete.

    Version 6

    Beta (v0.0.1)

    Live stream Post

    Prior to creating a live stream post, it is crucial to create the live stream that will be included in the post data to ensure that the necessary information is accessible and can be linked to the post. This requires creating the live stream first, to obtain the data that will be used in creating the live stream post. For more information regarding live stream, please refer to

    As demonstrated in the code sample below, here's a way to create a live stream.

    hashtag
    Version 6

    hashtag
    Beta (v0.0.1)

    Upon successful completion of the live stream process, you can include the stream ID as a parameter when creating a live stream post, as demonstrated in the code sample below.

    Here's an explanation of the method's parameters:

    • text: This is a required parameter of type String, which represents the text content of the new post. You can pass in any text you want to include in the post, up to a maximum length of 20,000 characters.

    • streamId: The ID of the created live stream to include in a post.

    You can create a livestream post via AmityLiveStreamPostBuilder .

    AmityLiveStreamPostBuilder creates a text post and attaches a stream post as a first child. This builder requires the stream object id.

    We can build the post first by using AmityLiveStreamPostCreator.Builder. Then, use the same createPost method in AmityPostRepository and pass the streamId

    Flag/Unflag a Message

    hashtag
    Flag a Message

    The Chat SDK product also includes a flag method that allows users to flag messages in their app. Once a message is flagged, an indicator will appear in the Admin console, where an administrator can review and validate the flag. If the content is found to be in violation of your app's policies, it can be deleted from the app. On the other hand, if the content is not found to be in violation, the flag can be revoked.

    The flag method provides an essential tool for managing user-generated content in your app, ensuring that inappropriate messages can be quickly identified and removed. By integrating this method into your app's user interface, you can empower your users to take an active role in promoting a safe and respectful community.

    To use the function you simply need to identify the messageId that you'd like to flag.

    hashtag
    Unflag a Message

    Another useful feature is the unflag method, which enables users to revoke a previously flagged message. If a user flags a message by mistake or if the message is found not to violate your app's policies after review, the unflag method can be used to remove the flag from the message. It ensures that users have control over the content they flag and the ability to reverse their flag if necessary.

    Similar to the flag function, you simply need to identify the messageId that you'd like to unflag.

    hashtag
    Check if Message is Flagged

    The isFlaggedByMe method allows users to check whether they have previously flagged a particular message. This method provides a convenient way for users to keep track of the content they have flagged and to ensure that they are staying up-to-date with their moderation activities.

    By using the isFlaggedByMe method, your app's users can quickly determine whether they have already flagged a particular message and avoid duplicating their efforts.

    Subchannel

    Subchannels are the part of a channel. They are separate topics or chat thread inside a channel. Messages can be sent & received in subchannel. By default, a channel itself would also generate a main subchannel once it's created. You can create, update, delete & query subchannels inside a channel. For the sturcture and relationship of channels and subchannels, please visit .

    circle-info

    Limitations:

    Image Message

    hashtag
    Send an Image Message

    Image message is a type of message that includes an image file. It allows users to share visual information with others in a chat. Image messages can be used in a variety of ways, such as sharing photos with friends, sending documents, or any other visual content that needs to be shared quickly and easily. With image messages, users can easily convey information to others in a chat, making it a powerful tool for communication.

    When calling this function, you can provide the local image path on the device and the ID of the subchannel where the message will be sent. The SDK will create an image message with the specified image and send it to the subchannel.

    Delete User

    Delete User API is called to delete a user from the system. The display name of the deleted user is replaced with “Deleted User”. This API can be called only by admin users.

    circle-info

    Please note that this action is a hard delete, and all deleted data will be lost and cannot be recovered.

    When deleting a user, you can specify that the user should be marked as deleted but the user’s data should remain unchanged, or you can specify that all personal data associated with the user should be deleted:

    import { UserRepository } from '@amityco/js-sdk';
    
    const liveObject = UserRepository.getUser('userId');
    liveObject.on('dataUpdated', user => {
      // user is successfully fetched
    });
    userRepo.userForId('user123')
    let liveUser = UserRepository.getUser("some-user-id")
    userObject.on(“dataUpdated”, model => {
       // you can access user object as model here
      console.log(model.userId, model.displayName)
    })
    userRepo.getAllUsers()
    import { UserSortingMethod } from '@amityco/js-sdk'
    
    userRepo.getAllUsers(UserSortingMethod.DisplayName)
    normalPostStructure + {
      dataType: “image”,
      data: { imageId: File[“fileId”] }
    }
    userRepo.flag({ userId: 'user123' })
    userRepo.unflag({ userId: 'user123' })
    userRepo.flag({ userId: 'user123' })
        .then(() => {})
        .catch(() => {})
    userRepo.searchUserByDisplayName('Test User 1')
    const liveUserCollection = UserRepository.queryUsers({
        keyword?: string, 
        filter?: 'all' | 'flagged', 
        sortBy?: 'lastCreated' | 'firstCreated' | 'displayName'
    })
    
    // filter if flagCount is > 0
    // lastCreated: sort: createdAt desc 
    // firstCreated: sort: createdAt asc 
    // displayName: sort: alphanumerical asc
    
    liveUserCollection.on(“dataUpdated”, models => {
      models.map(model => console.log(model.userId))
    })
    import { MessageRepository } from '@amityco/js-sdk';
    
    const liveObject = MessageRepository.createTextMessage({
      channelId: 'channel1',
      text: 'Hello World!',
    });
    
    liveObject.on('dataUpdate', message => {
      console.log('message is created', message);
    });
    const liveObject = ChannelRepository.getChannel('channelId');
    
    liveObject.on('dataUpdated', channel => {
      // the number of unread messages
      console.log(channel.unreadCount);
    });
    const isJoined = await ChannelRepository.joinChannel({
    channelId: 'channel2'
    });
    import { ChannelMembershipRepository } from '@amityco/js-sdk';
    
    await ChannelMembershipRepository.leaveChannel({ 
      channelId: 'channelId', 
    })
    import { 
      ChannelRepository, 
      ChannelType, 
      ChannelFilter, 
      ChannelSortingMethod,
    } from '@amityco/js-sdk';
    
    let channels;
    
    const liveCollection = ChannelRepository.queryChannels({
      keyword: 'asd',
      types: [ChannelType.Conversation],
      filter: ChannelFilter.Member,
      isDeleted: false,
      tags: ['tag1'],
      excludeTags: ['tag2'],
      sortBy: ChannelSortingMethod.LastCreated
    });
    
    liveCollection.on('dataUpdated', models => {
      channels = models;
    });
    
    channels = liveCollection.models;
    import { ChannelRepository, MemberFilter } from '@amityco/js-sdk';
    
    let members;
    
    const liveCollection = ChannelRepository.queryMembers({ 
      channelId: 'channel1',
      memberships: [MemberFilter.Member],
      roles: ['role1'],
      search: 'asd',
    });
    
    liveCollection.on('dataUpdated', newModels => {
      members = newModels;
    });
    
    liveCollection.on('dataError', error => {
      console.error(error);
    });
    
    members= liveCollection.models;
    repository.banMembers({
      userIds: ['user1'],
    }).catch(error => {
      ...
    });
    repository.unbanMembers({
      userIds: ['user1'],
    }).catch(error => {
      ...
    });
    repository.muteMembers({
      userIds: ['user1'],
      period: 600,
    }).catch(error => {
      ...
    });
    repository.unmuteMembers({
      userIds: ['user1'],
    }).catch(error => {
      ...
    });
    import { StreamRepository, StreamResolutions } from '@amityco/js-sdk'
    
    const liveObject = StreamRepository.createStream({
      title: 'title',
      thumbnailFileId: 'fileId', // use FileRepository.createFile to upload the file and get the id
      description: 'description',
      resolution: StreamResolutions.HD,
      metadata: { customField: 'customValue' },
    });
    
    liveObject.on('dataUpdated', (stream) => {
      console.log(stream);
    });

    if the deleteAll parameter is set to true, all personal data (i.e. profile, photos, images, and files), message channels, posts and comments of the user will be deleted.

  • the markMessageDeleted parameter, when set to true, deletes all message channels and messages that the user has created

  • the hardDeletePost parameter, if set to true, deletes all posts created by the user as well as the comments, reactions, child posts and child comments of the corresponding post

  • the hardDeleteComment parameter, if set to true, deletes all comments and reactions of the user

  • hashtag
    What happens when a user is deleted?

    hashtag
    The user cannot be reactivated

    Once a user has been deleted from the system, the account cannot be reactivated under any circumstances. In order to protect the user account data, no other user will be allowed to reactivate the account after it has been deleted by the user.

    hashtag
    The user's system ID is still saved, but the username is deleted and replaced with "Deleted User"

    The user's system ID will still be stored in the database, but to protect the user's identity, the account's username will be replaced with the text "Deleted User". All deleted accounts will be marked as "Deleted Account".

    hashtag
    All conversation channels created by the user will be deleted.

    If the user account is deleted, all conversation channels created by that user will be deleted immediately and no other user will be able to access those channels afterwards.

    hashtag
    All messages, channel names, and file attachments that the User created will be deleted

    After the account is deleted, all messages for all channels and all attachments that created by the user are deleted and cannot be restored.

    hashtag
    Channel member count will be updated

    When a user is deleted, the channel members are updated in all channels where the user was a member, so that only active users are counted in the channels.

    hashtag
    All user-related data will be permanently deleted and cannot be recovered

    All the user's data, including profile, photos, videos, images, text, audio, video, attachments, files and anything else that the user has added to the system as a user will be permanently deleted from the system and cannot be recovered.

    hashtag
    Posts, comments and associated IDs, as well as subordinate posts and subordinate comments of the user will be marked as deleted

    All posts created/shared by the deleted user will be deleted and all comments added by the deleted user will also be removed from all posts. No comments or sub-posts will be available after the user deletes the account.

    hashtag
    Reaction and comment count will be updated

    All reactions and comments posted by the deleted user are detected and updated in the posts.

    hashtag
    User will be marked as deleted when queried

    The status of the user's account is marked as "deleted" when queried and the user can no longer access it.

    hashtag
    API Parameters

    hashtag
    Headers

    Content-type
    application/json

    Authorization

    Bearer{{Admin Token}}

    hashtag
    Path

    Path
    Data field

    UserID

    User public id

    API response will be different based on the request and records match. The request may have successful response , or it may have bad request error, and it may respond as User not found. As the responses of API call are mentioned below.

    hashtag
    Success

    circle-check

    {

    "success":true

    }

    hashtag
    Bad Request error

    circle-exclamation

    { "status": "error",

    "code": 400000,

    "message": "User is already deleted"

    }

    hashtag
    User Not Found error

    circle-exclamation

    { "status": "error",

    "code": 400400,

    "message": "User Not Found."

    }

    Refer to Upload Files for the sample code on how to upload a file to get fileId.

    Version 6

    Beta (v0.0.1)

    Upload Files
    - Search for channels that the user is a member of
  • notMember - Search for channels that the user is not a member of

  • flagged - Search for channels that the user flagged

  • metadata
    - a flexible JSON object which can accommodate any information regarding the mentioned users. Our default structure for representing mentions is also in the metadata property.
    userId
    - userId of the user being mentioned. If the type of the mention is channel, then
    userId
    is undefined.
  • length - length of the mention

  • and
    CommentRepository.editTextComment
    along with other parameters to conveniently highlight across the platforms.
    Mention in Comment
    Mention in Messages
    notification setting APIarrow-up-right
    lastHeartbeat
    timestamp is mapped to the
    lastHeartbeat
    property of the
    AmityUser
    object, if available. Users can directly access the
    lastHeartbeat
    property from the
    AmityUser
    object to determine whether a user is online or offline.

    Id of the user

    lastHeartbeat

    Timestamp when that user last synced its heartbeat with the server.

    isOnline

    Convenient property to determine online status. User is considered online if its lastHeartbeat has been within last 60 seconds.

    Observe User Presence
    Followers/Following Collection
  • Channel Collection

  • Message Collection

  • Channel Member Collection

  • Community Collection

  • Community Members Collection

  • Single - emits exactly one element

    • doOnSuccess

    • doOnError

  • Completable - emits a “complete” event, without emitting any data type, just a success/failure

    • doOnComplete

    • doOnError

  • pagingData
    https://developer.android.com/topic/libraries/architecture/paging/load-state#adapterarrow-up-right
    RxJava3 operatorsarrow-up-right

    The name of the channel this message was created in

    ​Content

    userId

    string

    The name of the user this message was created by

    ​Content

    type

    string

    The message type

    enum*: text custom image file

    data

    Object

    The message data (any text will be stored in text key)

    text: Text message

    isDeleted

    boolean

    The message has been marked as deleted

    ​Content

    createdAt

    date

    The date/time the message was created at

    ​Content

    updatedAt

    date

    The date/time the message was updated at

    ​Content

    messageId

    string

    The id of this message

    ​Content

    channelId

    string

    reference
    reference
    (
    String
    ) - ID of the message to edit/update
  • data (String) - new message

  • Version 6

    Beta (v0.0.1)

    Query and Filter Messages
    targetType - Type of the target, either a particular community or a user feed.
  • tags - Arbitrary strings that can be used for defining and querying for the posts.

  • metaData - Additional properties to support custom fields.

  • from created
    AmityStream
    to create a livestream post.

    Version 6

    Beta (v0.0.1)

    Sub-channel creation is supported for Conversation and Community channel types.
  • Users can create up to 300 sub-channels per channel.

  • hashtag
    Create Subchannel

    In the concept of channels and subchannels, a channel is a primary container that can hold multiple subchannels. When you create a subchannel, it will serve as a thread where users can send messages and participate in discussions related to a specific thread. The subchannel creation function requires two parameters: channelId and displayName.

    • channelId: specifies the unique identifier of the parent channel where the subchannel will be created. This allows the SDK to link the subchannel to the correct parent channel, and organize it within the correct hierarchy.

    • displayName: Specifies the public name or label of the subchannel that will be visible to users.

    We don't support this feature in JS SDK.

    Version 6

    Beta (v0.0.1)

    hashtag
    Update Subchannel

    When you update a subchannel's properties, the changes will be reflected for all users who are members of that subchannel. Please note that the updateSubChannel function only updates the properties of the subchannel itself, and does not affect any messages or other content that has been sent within the subchannel.

    The function requires two parameters: subchannelId and displayName.

    • subhannelId: This is the unique identifier of the subchannel that you'd like to update.

    • displayName: This is the updated public name or label of the subchannel that will be visible to users.

    We don't support this feature in JS SDK.

    Version 6

    Beta (v0.0.1)

    hashtag
    Delete Subchannel

    The subchannelId parameter specifies the ID of the subchannel that you'd like to delete. The hardDelete parameter is a boolean value that determines whether to perform a hard delete or a soft delete.

    A soft delete will mark the subchannel as deleted but keep its data in the system. A hard delete will immediately and permanently delete the subchannel and all its data from the system.

    We don't support this feature in JS SDK.

    Version 6

    Beta (v0.0.1)

    hashtag
    Get Subchannel

    To get a subchannel, you can use the getSubchannel method provided by the SubchannelRepository. This method accepts a subchannelId parameter and returns a Live Object of the AmitySubchannel class.

    The AmitySubchannel class represents a subchannel in a channel. It contains information about the subchannel, such as its ID, display name, avatar, creation time, and more.

    By using a Live Object combines with Subchannel, you can observe any changes made to the subchannel in real-time. This is particularly useful in cases where multiple users may be interacting with the same subchannel and you need to keep the UI up-to-date with the latest data.

    We don't support this feature in JS SDK.

    Version 6 and Beta(v0.0.1)

    hashtag
    Query Subchannels

    The getSubChannels function allows you to retrieve a list of subchannels within a specific channel. It accepts the channelId parameter to specify which channel to retrieve subchannels from.

    The function returns a Live Collection, which allows you to observe changes to the collection in real-time.

    We don't support this feature in JS SDK.

    Version 6 and Beta(v0.0.1)

    For further information regarding a video information please refer to Image Handling page.

    Here is a brief explanation of the function parameters:

    • text/caption: A string that contains the text message that the user wants to send. This parameter is mandatory as it contains the actual message content.

    • attachment: The local image path that the user wants to send on the device

    • subchannelId: An identifier for the subchannel where the message will be sent. Subchannels are subdivisions within a channel that represent individual topics or chat threads. Messages and interactions occur within subchannels, not the main channel itself.

    • tags - Arbitrary strings that can be used for defining and querying for the messages.

    Version 6

    Version 5 (Maintained)

    Version 6

    To send an image in original size, set optional isFullImage() to true.

    Version 5 (Maintained)

    Here's a small example on how to create a message with an image attached. The process is pretty simple:

    1. Upload an image.

    2. Create a message with the uploaded image ID.

    circle-info

    Refer to for the sample code on how to upload a file to get fileId.

    Here's a small example on how to create a message with an image attached. The process is pretty simple:

    1. Upload an image.

    2. Create a message with the uploaded image ID.

    circle-info

    To send an image in original size, set optional isFullImage() to true.

    hashtag
    Image Upload & Sizing

    The SDK will resize and process the image object before sending it to the server. When an image is uploaded, it is automatically resized into multiple sizing options.

    The size of the image is determined by its longest dimension (in pixels) with the aspect ratios being unchanged. The maximum file size of an image cannot exceed 1 GB.‌ Amity will automatically optimize the image and when queried, will return the image in small, medium and large sizes.

    If the image is marked as isFull on upload, the original size of the image can also be returned. Note that this can drastically reduce the speed of message sending, depending on the original image size. If the fullImage is set to false, then the uploaded image size will be up to 1500x1500 pixel.

    You can also pass an optional caption as part of the message. This caption will be accessible under the data property in the message model, under the caption key. You can add up to 1,000 characters of text caption per message.

    circle-exclamation

    Supported image formats are JPG, PNG and HEIC and cannot exceed 1GB in size

    Unread Count

    Id of the Channel

    userPresences

    AmityUserPresence object for members whose presence state has been synced

    isAnyMemberOnline

    If any user's (except you) lastHeartbeat has been within last 60 seconds

    Observe Channel Presence

    User

    hashtag
    Identity

    Amity SDK's do not store or manage any user data. This means that you do not have to import or migrate existing user profiles into the system, user management should be handled by your application code. Instead, every user is simply represented by a unique userID, which can be any string that uniquely identifies the user and is immutable throughout its lifetime.

    A database primary key would make an ideal userID. Conversely, something like username or emails is not recommended as those values may change over time.

    If you wish to assign additional permissions for a user, for example, moderation privileges or different sending limits, you can provide an array of roles to assign to this user. Roles are defined in the admin panel and can be tied to an unlimited number of users. Once again, Amity does not store or manage any user data, which means you do not have to import or migrate existing users into the system. It also means that Amity cannot provide user management functionalities like list of users, or limit actions of certain users (e.g. user permissions). Instead, these functionalities should be handled by the rest of your application's capabilities and your server.

    hashtag
    Description of Users

    hashtag
    User Repository

    Though the SDK does not store and should not be responsible for the handling User profile data for your application; We do provide tools to make some surface-level queries and searches for existing user accounts. With the help of our UserRepository class, you will be able to list all the users, search for list of users whose display name matches your search query and get AmityUser object from user ID.

    hashtag
    Ban User

    You can ban a user globally. When users are globally banned, they can no longer access Amity's network and will be forcibly removed from all their existing channels.

    Refer documentation for instructions on how to globally ban a user.

    For more information please visit to

    Update User Information

    hashtag
    Update User Information

    Update current user information, including display name, avatar, user description, metadata, etc., using the updateUser method in the 'amityClient' class. This method updateUser accepts these optional parameters:

    The method accepts the following optional parameters:

    • displayName - user's display name

    • description - user's description

    • avatarFile - file ID of the user's avatar

    • avatarCustomUrl - custom url of the user's avatar

    • roles - user's role

    • metadata - user's metadata

    The updateCurrentUser method accepts the following optional parameters:

    • displayName - user's display name

    hashtag
    Update Current User's Avatar

    You can upload an image and set it as an avatar for the current user.

    First, you need to upload image using AmityFileRepository and then update the image info.

    Step 1 — Upload an image:

    Step 2 — Passing AmityImageData from step 1 into the builder, and call user update API.

    If you have an avatar present in your current system/server and just want to integrate that existing avatar to AmitySDK, you can just set the URL for the avatar directly.

    Note: getAvatarInfo

    Session State

    Session state is a key concept in the SDK that describes the authentication status of the client device. There are several session states that the SDK can be in, including:

    • notLoggedIn

    • establishing

    • established

    • tokenExpired

    • terminated

    The established state is the normal and fully authenticated state in which the SDK is usable. The other states represent different stages of the authentication process or an error condition.

    When SDK is initialized:

    • If the user is not logged in, the SDK starts in the initial "notLoggedIn" state.

    • If the user is already logged in, the SDK automatically resumes the logged-in session and immediately switches to the established state.

    circle-info

    When TS SDK is initialized, the session state always begins as notLoggedIn.

    When logging in:

    • If login succeeds, it moves to established state.

    • If login fails, it moves to notLoggedIn state.

    When logging out manually:

    • It moves to notLoggedIn state.

    When the user is logged in, but the user is banned or deleted from the system.

    • It moves to terminated state.

    circle-info

    The error code will be presented in terminated state. Please refer to for more details.

    When token has expired:

    • It moves to tokenExpired state.

    circle-info

    If the access token has expired, all network requests will fail. However, the SDK includes an automatic process for renewing the access token. As long as this process is implemented correctly, it is unlikely that the app will encounter this problem. Please refer to for more details.

    hashtag
    Read and Observe Session State

    The SDK provides APIs for reading and observing the session state.

    hashtag
    Implementing an app based on session state

    Session state is designed to align with the typical flow of an app. For example, developers can use the session state to guide app navigation, like this:

    hashtag
    Session Handler

    For logging, the SDK requires SessionHandler. SDK uses this object to communicate with the app when session handling is required. Currently, SessionHandler is used for:

    • Initiate access token renewal when it is about to expire or has expired.

    The code above shows a simple session handler. Please note that each function in SessionHandler can be customized to your app logic.

    hashtag
    Access Token Renewal

    When a user logs in to the SDK for the first time, an access token is issued that is valid for 30 days.

    If the access token is about to expire or has already expired, the SDK automatically initiates the renewal process through the sessionWillRenewAccessToken method of the SessionHandler.

    During the renewal process, the SDK passes an AccessTokenRenewal object to the app. The app must call either one of the following methods on this object to complete the process.

    Method on renewal object

    The following code shows how the app can implement the sessionWillRenewAccessToken method by providing an auth token for renewal.

    Social Realtime Events

    A topic is a distinct path that must be constructed for each model to which you wish to subscribe in real-time. The SDK provides helper methods to create these topics for each model type. Each topic encompasses an events enum, which developers can select to subscribe to based on their business context and interests.

    To subscribe to updates from a community or any content created within that community, the user must have the 'Member' status in that community. Once the user leaves the community, they will no longer receive real-time events.

    hashtag
    Community Topic

    • COMMUNITY - subscription to changes of the community object

    • POSTS - subscription to changes of post objects in the community

    • COMMENTS - subscription to changes of comment objects in the community

    • POST and COMMENTS - subscription to changes of post and comment objects in the community

    The default value is COMMUNITY

    The functionality isn't currently supported by this SDK.

    hashtag
    Post Topic

    • POST - subscription to changes of the post object

    • COMMENTS - subscription to changes of comment objects on the post

    The default value is POST

    The functionality isn't currently supported by this SDK.

    hashtag
    Comment Topic

    • COMMENT - subscription to changes of the comment object

    The functionality isn't currently supported by this SDK.

    hashtag
    User Topic

    • USER - subscription to changes of the user object

    • POSTS - subscription to changes of post objects in the user feed

    • COMMENTS

    The default value is USER

    The functionality isn't currently supported by this SDK.

    hashtag
    Follow Topic

    • MY_FOLLOWERS - subscription to changes related users that current user follows

    • MY_FOLLOWING - subscription to changes related users that follows current user

    The functionality isn't currently supported by this SDK.

    Messaging

    Messages are JSON content containers that can have up to 20,000 characters or can weigh up to 100KB for custom messages. They will be synchronized among all channel users in real-time. If a message requires larger binary data (such as when sending files), we recommend to upload the data to another cloud storage service, such as AWS S3, and store the URL to the content in the message data.

    In addition to the JSON message type, the SDK also provides support for common text and image message types. These additional types are built on top of the standard JSON message layer.

    The message payload is always the same regardless of which Development Kit the user is using. Users also have a choice on what type of message they want to send.‌

    hashtag
    Message Description

    hashtag

    Mention in Messages

    Mentions allow users to tag other users in messages. It's a powerful tool for fostering engagement and collaboration within your social application. With mentions, users can easily notify specific individuals or groups to new content or important updates. In the SDK, mentions can be implemented in a range of ways, depending on your application's needs and user experience. For more information about mentions, please refer to Mentions. We only support the ability to mention in only these channel types:

    • Community

    • Live

    hashtag
    Create Message with Mentions

    You can easily mention users when creating a message by including their user IDs in the mention user parameter as well as defining metadata for mention rendering. For further explanation, please refer to . We offer two types of mentions that can be included in a message:

    hashtag
    Mention Users

    When using this type of mention, up to 30 channel members can be notified through push notifications. Each individual member mentioned in the message will receive a notification.

    Version 6

    Version 5 (Maintained)

    Version 6

    Beta (v0.0.1)

    hashtag
    Mention Channel

    By specifying the channel ID in the mention channel parameter when creating a message, push notifications will be sent to all members of that channel when this type of mention is used.

    Version 6

    Version 5 (Maintained)

    Version 6

    Beta (v0.0.1)

    hashtag
    Update Message with Mentions

    We provide developers with an efficient method for updating messages with mentions of specific users, you can easily add mentions to their post updates and but it will not notify the relevant users.

    To remove mentions you can provide an empty JSON object for the metadata parameter, and an empty list for the mention users parameter. By doing so, You can easily remove mentions from the post content, while ensuring that the overall structure of the post remains intact.

    Version 6

    Beta (v0.0.1)

    The functionality isn't currently supported by this SDK.

    hashtag
    Render Mentions

    To render mentions in a supported feature, please refer to , specifically the section on handling mentions. This documentation provides detailed information on how to represent mentions in your application, including information on metadata structure, custom mention objects, and rendering support.

    hashtag
    Unread Mention Count

    When a member is mentioned(mention type could be channel as well) in a text message and the message is not read, then hasMention property is "true" in Channel class. Every time the hasMention property is true, this means that the member has an unread message with mention(message could be created or updated as well).

    Creating Typescript User Token
    Creating iOS User Token
    Creating Typescript User Token
    Updating Display Name and Tags
    image-text

    Install iOS SDK

    The Amity Social Cloud SDK for iOS is delivered as a binary .xcframework file

    hashtag
    Manual Installation

    • Drag AmitySDK.xcframework

    File Handling

    Files are an essential component of modern software applications. Amity provides a powerful file management system that enables you to easily handle different types of files, such as document files, videos, and audio files. In this section, we will introduce you to the concept of a file in Amity and provide an overview of file handling in Amity.

    hashtag
    File Data

    Property
    Description
    Upload Files

    Chat

    Amity Chat SDK allows you to easily create full-featured in-app Chat experience

    iOS ​ Android ​ Web TypeScript React Native Ionic Flutter

    hashtag
    Amity Chat SDK

    Video Handling

    hashtag
    Video Data

    The video data is the representation of the video that has been uploaded using the SDK. The uploaded video will be transcoded to other different resolutions depending on console settings. Below is a table of properties that it contains.

    Property
    Description
    Upload Videos

    Channel Moderation

    Channel Moderation is an essential feature for creating a safe and engaging chat community. With Amity Chat SDK, developers can use moderation to manage chat channels effectively and ensure that the chat community remains safe and welcoming. Moderation features such as user banning and muting can help prevent inappropriate content and maintain a positive chat environment.

    hashtag
    Add / Remove Roles

    define varying levels of access and permissions that can be assigned to users within a chat channel. Each role is defined by a set of permissions that determine what actions a user can perform within the channel.

    Send a Message

    Messaging is an essential component of any chat application, and the SDK provides robust messaging features. The SDK optimizes the messaging flow for users by instantly displaying sent messages, even before they have been delivered to the server. To ensure the user's smooth messaging experience, the SDK provides the syncState property in the message model to monitor the message delivery status.

    Amity supports the sending and receiving of five types of messages:

    Query and Filter Messages

    hashtag
    Querying Messages

    The getMessages function is a powerful feature of the chat or messaging SDK that allows users to retrieve messages from a specific subchannel based on various criteria. This function provides flexibility in fetching messages that meet specific requirements. This function returns a of messages.

    Filter parameters

    Install Android SDK

    The Amity Social Cloud SDK for Android is delivered via Jitpack repository.

    hashtag
    Requirements

    • Android 5.0 (API level 21) and above*

    import { MessageRepository, MessageType  } from '@amityco/js-sdk';
    
    // this function takes in input a File from a <input type="file" />
    const createFileMessage = (file: File) => {
      // first, create the file object.
      const liveFile = FileRepository.createFile({ file })
    
      // second, create the message object with the fileId from the liveFile
      const liveMessage = MessageRepository.createFileMessage({
        channelId: 'my-channel',
        fileId: id, // id of the file created with FileRepository.createFile
        caption: 'have a look!',
        tags: ['tag1', 'tag2'],
      })
    }ja
    {
      "level": "network",
      "isPushNotifiable": true,
      "notifiableEvents": [
       {
          "name": "text-mention-message.created",
          "isPushNotifiable": true,
          "titleTemplate": "{{UserDisplayName}} mentioned you in {{ChannelName}}",
          "bodyTemplate": "{{Message}}"
        }
      ]
    }
    implementation "androidx.paging:paging-compose:x.y.z"
    try {
      const isAdded = await MessageRepository.addReaction({
        messageId: 'messageId', 
        reactionName: 'love',
      });
      
      if (isAdded) {
        console.log('reaction is added');
      }
    } catch (error) {
      console.error('can not add reaction', error);
    }
    try {
      const isRemoved = await MessageRepository.removeReaction({
        messageId: 'messageId', 
        reactionName: 'love',
      });
      
      if (isRemoved) {
        console.log('reaction is removed');
      }
    } catch (error) {
      console.error('can not remove reaction', error);
    }
    
    import { MessageRepository } from '@amityco/js-sdk';
    ​
    try {
      await MessageRepository.deleteMessage('messageId');
      console.log('message is deleted');
    } catch (error) {
      console.error('can not delete message', error);
    }
    
    import { MessageRepository } from '@amityco/js-sdk';
    ​
    try {
      await MessageRepository.updateMessage({ 
        messageId: 'messageId', 
        data: { text: 'new text' },
      );
      console.log('message is updated');
    } catch (error) {
      console.error('can not update message', error);
    }
    import { MessageRepository } from '@amityco/js-sdk';
    
    const messageLiveObject = MessageRepository.createTextMessage({
      channelId: 'channel1',
      text: 'Hello World!',
      parentId: 'exampleParentMessageId,
      tags: ['tag1', 'tag2'],
      mentionees: [
        {
          "type": "user",
          "userIds": [
            "user1", “user2”
          ]
        }
      ]
    });
    // start reading a channel
    await ChannelRepository.startReading({ channelId: 'channel1' });
    
    // stop reading a channel
    await ChannelRepository.stopReading({ channelId: 'channel1' }); 
    import { MessageFlagRepository } from '@amityco/js-sdk';
    const flagRepo = new MessageFlagRepository('message1');
    flagRepo.flag()
    flagRepo.unflag()
    const result = await flagRepo.isFlaggedByMe()

    string

    The messageId of the parent of this message

    ​Content

    childrenNumber

    integer

    The number of messages with parentId of this message

    ​Content

    channelId

    string

    The name of the channel this message was created in

    ​Content

    userId

    string

    The name of the user this message was created by

    ​Content

    type

    string

    The message type

    enum*: text custom image file

    tags

    Array.<string>

    The message tags

    ​Content

    data

    Object

    The message data (any text will be stored in text key)

    text: Text message

    isDeleted

    boolean

    The message has been marked as deleted

    ​Content

    createdAt

    date

    The date/time the message was created at

    ​Content

    updatedAt

    date

    The date/time the message was updated at

    ​Content

    editedAt

    date

    The date/time the message was edited at

    ​Content

    flagCount

    integer

    The number of users that have flagged this message

    ​Content

    reactions

    Object

    The reaction data (stored as a reactionName and counter key/value pair)

    Example: { like: 1, dislike: 2 }

    reactionsCount

    integer

    The total number of reactions on this message

    ​Content

    myReactions

    Array.<string>

    A list of user's reactions on this message

    ​Content

    Name

    Data Type

    Description

    Attributes

    messageId

    string

    The id of this message

    ​Content

    parentId

    Search users by display name
    Query users
    Target sdk version 29 and above*
  • Compile SDK Version 29 and above*

  • JVM target should be 1.8

  • The API level allows a developer to declare the minimum version with which the app is compatible, using the minSdkVersion attribute. If your app can't function without these APIs, declare API level 21 and above as the app's minimum supported version. And using targetSdkVersion 29 and above.

    hashtag
    Installation

    Add the Jitpack repository in your project level build.gradle at the end of repositories:

    dependencyResolutionManagement {
      repositories {
        ...
        maven { url 'https://jitpack.io' }
      }
    }
    allprojects {
      repositories {
        ...
        maven { url 'https://jitpack.io' }
      }
    }

    Add the dependency in your module level build.gradle. Find latest SDK version at Changelog.

    hashtag
    Android API level below 24

    If your minSDKVersion is below 24, ie., 23 or 21, there are additional configurations required.

    In your project build.gradle,

    hashtag
    Managing conflicting file generation

    In your app module's build.gradle, add the following packaging options.

    hashtag
    Code Obfuscation

    By using our SDK, you can use the Android ProGuard tool to obfuscate, shrink, and optimize your code. Obfuscated code can be more difficult for other people to reverse engineer. ProGuard renames classes, fields, and methods with semantically obscure names and removes unused code. However, you need to add these configurations to your ProGuard rules when using our SDK.

    For users who are using the SDK version below 5.33.11 and 6.9.0. If you'd like to pass an Amity Serializable Object such as AmityPost, AmityMessage, etc. You will need to add an additional ProGuard rules below:

    hashtag
    Amity SDK Log Visibility

    For debugging purposes, we provide the ability to show or hide logs from our SDK. In the 'build.gradle' application, you can set the boolean value resValue "IS HIDDEN AMITY LOG" to true to hide the logs and to false to make them visible.

    In the 'build.gradle' application, you can also customize the log display depending on the build variant, as in this example.

    implementation 'com.github.AmityCo.Amity-Social-Cloud-SDK-Android:amity-sdk:x.y.z'
    implementation("com.github.AmityCo.Amity-Social-Cloud-SDK-Android:amity-sdk:x.y.z")
    android {
        ...
        defaultConfig {
            minSDKVersion 21 // at least 21
        }
    }
    buildscript {
        repositories {
            google()
            gradlePluginPortal()
            ...
        }
        dependencies {
            ...
            classpath 'gradle.plugin.com.github.sgtsilvio.gradle:android-retrofix:0.4.1'
        }
    }
    android {
        ...
        packagingOptions {
            exclude 'META-INF/INDEX.LIST'
            exclude 'META-INF/io.netty.versions.properties'
        }
    }
    -keep class com.ekoapp.ekosdk.** { *; }
    -keep interface com.ekoapp.ekosdk.** { *; }
    -keep enum com.ekoapp.ekosdk.** { *; }
    -keep class com.amity.socialcloud.** { *; }
    -keep interface com.amity.socialcloud.** { *; }
    -keep enum com.amity.socialcloud.** { *; }
    -keep class co.amity.rxupload.** { *; }
    -keepclassmembers class * implements java.io.Serializable {
    private static final java.io.ObjectStreamField[] serialPersistentFields;
    private void writeObject(java.io.ObjectOutputStream);
    private void readObject(java.io.ObjectInputStream);
    java.lang.Object writeReplace();
    java.lang.Object readResolve();
    }
    android {
        defaultConfig {
            resValue 'bool', "IS_HIDDEN_AMITY_LOG", "true"
            …
        }
        …
    }
    android {
        def IS_HIDDEN_AMITY_LOG = "IS_HIDDEN_AMITY_LOG"
        
        buildTypes {
            release {
                resValue 'bool', IS_HIDDEN_AMITY_LOG, "true"
                …
            }
            debug {
                resValue 'bool', IS_HIDDEN_AMITY_LOG, "false"
                …
            }
        }
    
    }
    Refer to Upload Images for the sample code on how to upload a file to get fileId.

    Version 6

    Beta (v0.0.1)

    Upload Images

    Array.<string>

    A list of user's roles

    displayName

    string

    The display name of the user

    flagCount

    integer

    The number of users that have flagged this user

    metadata

    Object

    The metadata of the user

    hashFlag

    Object

    A hash for checking internally if this user was flagged by the user

    createdAt

    date

    The date/time the user was created at

    updatedAt

    date

    The date/time the user was updated at

    isGlobalBan

    Boolean

    Flag that indicates if the user is globally banned. True means the user is globally banned.

    Note: This is not yet supported for Typescript

    avatarCustomUrl

    String

    Custom Url provided for this user avatar

    isDeleted

    Boolean

    Flag that indicates if the user is deleted

    Name

    Data Type

    Description

    Attributes

    userId

    string

    The id of this user

    global ban
    User & Content Management

    roles

    description - user's description
  • avatarFile - file ID of the user's avatar

  • avatarCustomUrl - custom url of the user's avatar

  • roles - user's role

  • metadata - user's metadata

  • Below is a sample code on how to update the current user's display name, description, and metadata. This method returns a promise. If the update is successful, the method will return true, else it throws an error.

    hashtag
    Flag/Unflag Users

    To flag a user, call the following method:

    To unflag a user, call the following method:

    To check if the user is flagged by the current user:

    provides the information associated with a particular Avatar

    First, you need to upload image and then update the image info. If you have an avatar present in your current system/server and just want to integrate that existing avatar to AmitySDK, you can just set the URL for the avatar directly.

    If you have an avatar present in your current system/server and just want to integrate that existing avatar to AmitySDK, you can just set the URL for the avatar directly.

    Either you wish to let us handle your user's avatar, or if you already have a system for it we got you covered. The 2 properties avatarFileId and avatarCustomUrl answer those two use-cases separately.

    You can easily retrieve the url of a file from our FileRepository object and use it to display in your app later on. Here's an example in React:

    You can easily retrieve the url of a file using observeFile and use it to display in your app later on. Here's an example in React:​

    - subscription to changes of comment objects in the user feed
  • POST and COMMENTS - subscription to changes of post and comment objects in the user feed

  • ,
    Realm.xcframework
    &
    RealmSwift.xcframework
    to your project.
  • Make sure that Copy items if needed is selected and click Finish.

  • Also switch the Embed section as Embed & Sign

  • The correct setup should look like this.

    circle-info

    You need to turn Rosetta mode on when using AmitySDK with arm64 simulator. To force the application to use Apple Rosetta environment with an Apple silicon Mac, refer to this pagearrow-up-right for the instructions.

    hashtag
    Using Dependency Manager

    AmitySDK supports installation via dependency managers.

    • SwiftPM

    • Cocoapods

    • Carthage

    hashtag
    SwiftPM Installation

    To integrate AmitySDK into your project via SwiftPM, please follow the instruction below.

    • Add a Package Dependencyarrow-up-right

    Enter the repository URL to search the package, and choose to install AmitySDK.

    circle-exclamation

    If you selected "Up to Next Major Version" option for the Dependency Rule, you need to manually add the version.

    hashtag
    Carthage Installation

    ​Carthagearrow-up-right is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate the Amity Social Cloud SDK, add the following line of code to your Cartfile.

    hashtag
    Cocoapods Installation:

    To integrate the Amity Social Cloud SDK into your Xcode project using CocoaPods, specify the following lines of code in your Podfile:

    This installs the latest version of SDK. To get more info about our latest release, please look into changelog section. We support cocoapod installation of our sdk above version 5.1.0. The minimum deployment target platform for iOS is 12.0. If there are any issues during installation steps, clean cocoapods cache and try again. To clear cache please go to ~/Library/Caches/Cocoapods and remove `AmitySDK` related folders/files.

    If this doesn't work, please do visit the Cocoapods Githubarrow-up-right repo for further resolutions.

    circle-exclamation

    AmitySDK already includes our UIKit. Don’t install the UIKit separately if you have already installed the SDK.

    hashtag
    Additional Steps for Amity Video

    Amity Video requires the AmitySDK as dependencies. First, ensure you have installed the AmitySDK as per the instructions above.

    To use live video broadcast:

    • Import AmityLiveVideoBroadcastKit.xcframework to your project.

    To use live video player:

    hashtag
    For version 6.0.0 - 6.7.0

    • Import AmityVideoPlayerKit.xcframework to your project

    • Download MobileVLCKit.xcframeworkarrow-up-right, and import to your project.

    • Switch each framework to Embed & Sign, except MobileVLCKit to Do Not Embed.

    For the project that uses both live video broadcast and live video player, the correct setup should look like this.

    To install Swift Packages for Amity Video, please follow the instructions below.

    • Add a Package Dependencyarrow-up-right

    hashtag
    For version 6.8.0 and above

    • Import AmityVideoPlayerKit.xcframework to your project

    • Download MobileVLCKit.xcframeworkarrow-up-right, and import to your project.

    • Switch each framework to Embed & Sign, all xcframeworks.

    For the project that uses both live video broadcast and live video player, the correct setup should look like this.

    hashtag
    Amity Video with SwiftPM

    To install Swift Packages for Amity Video, please follow the instructions below.

    • Add a Package Dependencyarrow-up-right

    hashtag
    1. Install AmityVideoBroadcast

    To use live video broadcast functionalities. Enter the repository URL to search the package, and choose to install AmityVideoBroadcast.

    Try it in your code

    hashtag
    2. Install AmityVideoPlayer

    To use live video player functionalities. Enter the repository URL to search the package, and choose to install AmityVideoPlayer.

    Try it in your code

    circle-exclamation

    If you selected "Up to Next Major Version" option for the Dependency Rule, you need to manually add the version.

    hashtag
    Using AmitySDK with Objective C Code

    Starting with v6.0.0, AmitySDK for iOS is written in Pure Swift. Although its in pure Swift, you can still use it in Objective-C projects by making Mixed-Language Project.

    We recommend you to integrate AmitySDK for iOS swift directly into your Objective-C project and use Swift language to call the SDK interfaces.

    hashtag
    Mixed Language Project:

    To make a mixed language project, create Swift files with necessary interfaces/methods which in turn interacts with AmitySDK. These interfaces should be exposed with @objc or @objcMembers attributes. Reference: Swift Attributesarrow-up-right

    When you add new Swift file into your Objective-C project, Xcode automatically generates a bridging header file. This bridging header exposes your Swift code to Objective C code. For more information you can refer to this guide by Apple: Importing Swift into Objective-Carrow-up-right

    Download the latest iOS SDKarrow-up-right

    fileId

    Root file key on cloud storage

    fileUrl

    HTTP link for file download

    type

    File type

    createdAt

    Date/time when a file is uploaded

    updatedAt

    hashtag
    Upload Files

    To upload a file to the system, you can use the Amity File Upload API provided by the SDK. The API allows you to upload a file to the Amity server by providing the file's data and the file metadata, such as the file name, file type, and file size. The SDK simplifies the process of uploading files by providing pre-built components that you can easily integrate into your application.

    On Android, you can separately observe uploading states outside of the uploading method by using:

    Version 6 and Beta(v0.0.1)

    hashtag
    Retrieve Files

    You can retrieve a file from Amity using the Amity File Retrieval API provided by the SDK. The API enables you to retrieve a file from the Amity server by supplying the file ID. The SDK streamlines the process of retrieving files by offering pre-made components that can be smoothly integrated into your app.

    hashtag
    Delete Files

    In addition to uploading and retrieving files, Amity provides a deleting function to delete a file that is no longer needed.

    The response will return true if the file deletion is successful.

    Version 6 and Beta(v0.0.1)

    The response will return true if the file deletion is successful.

    Otherwise, if an error is encountered during the deletion, it will return the following errors:

    The Amity Chat SDK provides a powerful set of pre-built features to enable in-app social experiences and fuel user engagement. With support for a range of platforms and programming languages, the SDK is a flexible and scalable solution for building messaging apps. We hope this documentation page has provided you with the information you need to get started with the SDK. If you have any questions or feedback, please feel free to contact us via our support center.

    We provide a range of pre-built features that enable in-app social experiences and fuel user engagement. Here are some of the main features of the SDK:

    • Start a new conversation channel with up to 300,000 concurrent participants (actual maximum may varies from selected plan, see pricingarrow-up-right for more detail)

    • View read counts for every message

    • Moderate conversations with user banning, muting, and rate limiting

    • Assign moderators and admins via a role-based permission system

    • Filter out inappropriate content with automated spam filtering and URL whitelists

    • Manage connection state and handle offline data automatically

    • Support multi-device and multi-platform for every user

    • Powerful messaging capabilities for native and web apps

    • Moderation tools for filtering out inappropriate content

    • Role-based permission system for assigning moderators and admins

    • Real-time syncing of messages across all users in a channel

    • Support for text, image, audio, video, file, and custom messages

    • Support up to 300,000 concurrent participants in a channel

    hashtag
    Getting Started

    Channel is a virtual chat room or a group that enables users to send and receive messages in real-time. Channels allow developers to implement different types of chat messaging capabilities into their applications easily, such as private messaging, group chats, and chat rooms.

    If you're new to the Amity Chat SDK, the following resources can help you get started:

    • Installation Guide

    • Authentication Guide

    hashtag
    Channel Types

    Messaging is a crucial feature for any chat application, and with Amity Chat SDK, developers can enable real-time communication between users within a chat channel with ease.

    The Amity Chat SDK supports several channel types, each designed to match a particular use-case for chat channels. Here's a table showing what features each channel type offers:

    Channel Type
    Discoverable by
    Message Sending Privileges
    Moderation Access
    Channel Creation

    Community

    All members and admins

    Members and admins

    All Moderation tools

    hashtag
    Message Types

    Moderation is an essential feature for building a community that encourages user participation and engagement. With Amity Chat SDK, developers can use the moderation feature to assign moderators and admins via a role-based permission system, filter out inappropriate content with automated spam filtering and URL whitelists, and manage user bans.

    The Amity Chat SDK supports several message types, including:

    Chat experience is more fun when you can express yourself! With Amity Chat SDK, developers can use Reactions feature to allow users to react to messages using emojis, stickers, or thumbs up. This feature can help users express their emotions and opinions, making communication more engaging and interactive.

    • Text Message

    • Image Message

    • File Message

    • Audio Message

    • Video Message

    • Custom Message

    In addition to these message types, the SDK also supports message reactions, which can be used to enable users to react to messages in a channel.

    hashtag
    Features

    hashtag
    Channels

    Our channels enable developers to implement different types of chat messaging capabilities into their applications easily.

    hashtag
    Messaging

    This page highlights the steps you will need to follow to begin integrating chat messaging into your products.

    hashtag
    Moderation

    Moderation is an important feature for building a safe community that encourages user participation and engagement.

    hashtag
    Reactions

    Interactions are more fun when you can express yourself! Let users react using emojis, stickers, or thumbs up to messages.‌

    arrow-up-right

    fileId

    Identifier for the uploaded file

    fileUrl

    The HTTP web URL for the uploaded file. You can use this fileUrl for downloading the original video file. (The file format remains unchanged)

    attributes

    Contains a dictionary with values for name, extension, size and mimeType of uploaded video.

    attributes.metadata

    Contains a dictionary with values for video and audio of uploaded video.

    attributes.metadata.video

    Contains a dictionary with values for width, height, duration, bit_rate, avg_frame_rate and display_aspect_ratio

    attributes.metadata.audio

    Contains a dictionary with values for duration, bit_rate and sample_rate

    videoUrl

    After video uploaded and transcoded by the server. The video data will contain videoUrl that provides different video URLs for each resolution.

    1. original - the equivalent resolution to fileUrl

    2. 1080p - 1920×1080 in horizontal, and 1080x1920 in vertical

    status

    An enum represents 4 video statues

    1. uploaded - the video is uploaded and users can watch the original raw file on fileUrl

    2. transcoding - the video is being transcoded to pre-defined resolutions

    circle-info

    The fileUrl and videoUrl.original provides the URL of the same video resolution. The difference being, fileUrl returns the actual file format while videoUrl.original returns MP4 format.

    hashtag
    Upload Videos

    To upload a video to the system, you can use the Amity Video Upload API provided the SDK. The API allows you to upload a video to the Amity server. The SDK simplifies the process of uploading videos by providing pre-built components that you can easily integrate into your application.

    Supported ✅ (please wait while we prepare a real example!)

    Version 6 and Beta(v0.0.1)

    If an error is encountered while creating the file, it will return the following errors:

    hashtag
    Retrieve Videos

    hashtag
    Get a Specific Video Resolution

    Once you uploaded a video the videos undergo transcoding from their original resolution. You can quickly access the original size of the video right after you make the video message. However, it takes time for the transcoded resolutions to be ready. Here are the available transcoded resolutions.

    • 1080p

    • 720p

    • 480p

    • 360p

    • original

    Supported ✅ (please wait while we prepare a real example!)

    Here's an example of getting a specific video resolution from a post.

    hashtag
    Get a Video Thumbnail Image

    Additionally, you can display a video preview in the user interface by utilizing a video thumbnail image. This allows for a more visually appealing representation of the video and provides a quick preview for users before they choose to view the full video. The thumbnail may not immediately available after the video was uploaded. However, eventually, the thumbnail will be become available.

    Supported ✅ (please wait while we prepare a real example!)

    Supported ✅ (please wait while we prepare a real example!)

    The functionality isn't currently supported by this SDK.

    Roles can be assigned to users based on factors such as their level of participation in the chat community or their specific responsibilities within the channel. For example, a moderator might have the ability to remove inappropriate messages or ban users from the channel, while a regular user might only have the ability to send and receive messages.

    You can use ChannelRepository class to add / remove users from a role

    Supported ✅ (please wait while we prepare a real example!)

    Supported ✅ (please wait while we prepare a real example!)

    circle-info
    1. The channel creator is automatically assigned as the channel moderator.

    2. The previous/last moderator is not allowed to leave a community and an error is displayed.

    3. The channel moderator can promote a user/member to moderator.

    4. The channel moderator can demote a moderator to a user/member.

    This applies only to Live and Community channels’. This does not apply to Conversation Channel.

    hashtag
    Permission

    You can check your permission in channel by sending Permission enums to CoreClient.hasPermission(amityPermission).

    Supported ✅ (please wait while we prepare a real example!)

    The functionality isn't currently supported by this SDK.

    Supported ✅ (please wait while we prepare a real example!)

    hashtag
    Add / Remove Members

    AmityChannelMembership provides methods to add and remove members, as well as removing yourself as a member of the channel (leaving the channel).

    • channelId: The ID of the channel to which you want to add or remove members.

    • userIds: An array of user IDs to be added to the channel or removed from the channel.

    Version 6

    Add Channel Members

    Remove Channel Members

    Beta (v0.0.1)

    Add Channel Members

    Remove Channel Members

    The functionality isn't currently supported by this SDK.

    hashtag
    Ban / Unban Members

    ChannelRepository class also provides various methods to moderate the users present in channel. You can ban/unban users, assign roles or remove it from user.

    For the banMembers function, the following parameters are required:

    • channelId: The ID of the channel from which the members are being banned.

    • userIds: An array of user IDs to be banned from the channel.

    For the unbanMembers function, the following parameters are required:

    • channelId: The ID of the channel from which the members are being unbanned.

    • userIds: An array of user IDs to be unbanned from the channel.

    Version 6

    Ban members

    Unban members

    Beta (v0.0.1)

    Ban members

    Unban members

    Supported ✅ (please wait while we prepare a real example!)

    Roles
    Image Message
  • Video Message

  • Audio Message

  • File Message

  • Custom Message

  • hashtag
    Message Synchronization

    SDK (Android & iOS) now supports resynchronization of message if the internet connection is not available or interrupted at the time the user sends a message. To support resynchronization, we enhanced the internal architecture on how the messages are queued, processed and synced with server.

    hashtag
    Local Message

    When you create a message, SDK first creates the message locally. This locally created message will be reflected immediately in the related live collection that user is observing at the moment. Then the SDK starts syncing this message with server. User can check the syncState property of the message model inside live collection to reflect the current state of the message.

    hashtag
    Message Syncing

    Once a message is created locally, SDK adds the message to the queue and starts the process of syncing this message with server. After the message is synced with server, the syncState of the message changes to synced. Here is the table showing various state of the message and its corresponding syncState value per platforms.

    Message State
    iOS
    Android

    When message is created locally and waiting in queue for syncing to server

    syncing

    created

    When message is being synced to server

    syncing

    syncing

    The messages are synced in the order they get added to the queue in FIFO (First In First Out) order. SDK will maintain causal ordering of the message of similar types.

    hashtag
    Causal Ordering:

    SDK maintains causal ordering for similar type of messages i.e (Text, Custom) & (Image/File/Audio/Video). Let’s look at the example to understand this:

    If user creates messages in this order from left to right: [Text1 → Image1 → Image2 → Text2 → Text3 → Image3]

    • The ordering of text messages are maintained i.e Text 2 will be synced after Text 1 & so on

      • [Text1 → Text2 → Text3]

    • The ordering of Media messages are respected i.e Image2 will be synced after Image 1 and so on.

      • [Image1 → Image2 → Image3]

    • The ordering of all messages mixed might not be respected. Ex: If image1 takes longer time to upload, the ordering can be:

      • [Text1 → Text2 → Text3 → Image1 → Image2 → Image3]

    hashtag
    Waiting for connectivity:

    SDK automatically determines the internet connection availability on user device and waits for the stable connection before sending the request to sync with server. Once the connection is available, SDK syncs the message with the server maintaining the causal ordering as described above.

    hashtag
    Connection Interruption / Server Error Handling

    If the network connection is interrupted during the request or server returns error for the request, depending upon the interruption state & error returned, SDK will automatically retry syncing the message after some interval (~ 5 seconds). SDK will retry syncing up to maximum 3 times and if the message still cannot be synced, SDK will mark the message as failed and notify the user through callback of createMessage api. The syncState of the message would change to failed / error.

    hashtag
    Failed Message Handling

    The message syncing can fail for many reasons. User should handle the error thrown from create message api and decide what to do for failed messages. Once the status of the message is failed, SDK will not attempt to retry syncing that message anymore. The failed messages will not be automatically removed from the live collection. It’s up to the user to decide if they should resend the same message or delete the failed message so that it disappears from the live collection. The syncState of the failed message would be failed / error.

    hashtag
    Deleting failed message:

    You can use existing softDeleteMessage() method in AmityMessageRepository class to delete specific failed message.

    hashtag
    Deleting all failed messages:

    If you do not care about any failed messages, SDK also provides deleteFailedMessages() method in AmityMessageRepository class to allow deletion of all failed messages.

    hashtag
    Deleting all failed messages upon SDK Initialization:

    This message syncing process is only maintained per active session per device. If user logs out or if user current session is destroyed, all the active syncing process is terminated.

    When the SDK is initialized again (i.e client instance is initialized), all the messages which were in syncing state from the previous session would be changed to failed state. User can choose to delete particular failed message (using softDeleteMessage() method) or delete all failed messages (using deleteAllFailedMessages() method).

    Text Message

    subChannelId: This parameter specifies the ID of the subchannel from which you want to retrieve messages.

  • includingTags[] (optional): This parameter allows you to filter messages based on specific tags. You can provide an array of tags, and the function will return only the messages that have at least one of the specified tags.

  • excludingTags[] (optional): Conversely, this parameter allows you to exclude messages that have certain tags. You can specify an array of tags, and the function will exclude messages with any of the specified tags from the result.

  • includeDeleted (optional): This parameter determines whether to include deleted messages in the result. If set to true, the function will include both active and deleted messages. If set to false, only active messages will be returned.

  • type (optional): You can filter messages according to their type

    • if no type is passed, any message will match

    • if an AmityMessage.DataType is passed, query for all messages with the specific type

      • AmityMessage.DataType.TEXT for text messages

      • AmityMessage.DataType.IMAGE for image messages

      • AmityMessage.DataType.FILE

  • Sorting

    In the getMessages function, the sorting option allows you to specify how the returned messages should be ordered. There are two available sorting options:

    1. firstCreated: When you set the sorting option to firstCreated, the messages will be ordered in ascending order based on their creation time. This means that the oldest messages will appear first in the returned collection, while the newest messages will be at the end.

    2. lastCreated: On the other hand, when you choose the lastCreated sorting option, the messages will be ordered in descending order based on their creation time. This means that the newest messages will appear first in the returned collection, while the oldest messages will be at the end.

    By utilizing the getMessages function with these parameters and sorting option, you can retrieve messages from a specific subchannel while applying additional filters based on tags and including or excluding deleted messages. This provides a flexible and efficient way to fetch and manage messages within your chat or messaging application.

    Version 6

    Version 5 (Maintained)

    Version 6

    Version 5 (Maintained)

    Version 6

    Beta (v0.0.1)

    .

    hashtag
    Threaded Messages

    Querying threaded messages allows users to retrieve the replied (children) messages associated with a specific message thread. When a message serves as the root of a thread, you can use the parentId parameter in a message query to fetch its child messages.

    To query threaded messages, you can add the following parameters to your message query:

    • parentId: This parameter specifies the ID of the parent message. By providing the parentId, you are indicating that you want to retrieve the child messages associated with that specific parent message.

    • filterByParentId: This flag enables the filtering of messages based on their parent ID. By setting this flag, the query will only return messages that have the specified parentId.

    By including the parentId parameter and setting the filterByParentId flag in your message query, you can retrieve the child messages of a particular message thread. This functionality allows for structured and organized conversations within your chat or messaging application, enabling users to navigate and explore threaded discussions with ease.

    Version 6

    Version 5 (Maintained)

    Version 6

    Version 6 and Beta (v0.0.1)

    Supported ✅ (please wait while we prepare a real example!)

    hashtag
    Navigating(Jump) to a specific message

    To locate a specific message within a chatroom, you can use the index of the message in the collection if known. However, there may be cases where the desired message, such as a reply to a much older message, is not in the current collection. In such instances, it's essential to perform a message query. The SDK offers an additional parameter for message queries called aroundMessageId, which retrieves the target message along with its preceding and following messages.

    Using a message query with aroundMessageId generates a new live collection. The application's decision to perform data swapping depends on the query's result. Typically, data swapping should not be executed in case of a business error, such as using an invalid target messageId or a messageId associated with a deleted message for aroundMessageId. Upon a successful query, the application can proceed with the source swap, locate the index of the target message, and scroll to that specific position.

    In cases where there is a business error but no existing source (e.g., entering a chatroom via push notification), the application can recover by querying for the latest message using a message query without aroundMessageId.

    After swapping the source, most, if not all, of the messages from the previous source will likely no longer be available in the new one. To enable users to navigate back to the message they jumped from, they can scroll through the pages manually. However, the application can also facilitate this by caching the messageId of the message they jumped from and offering a floating button as a shortcut to navigate back. This functionality can be achieved by leveraging a message query and using the cached messageId as the value for aroundMessageId.

    circle-info

    This feature is available exclusively from version 6.18.0 onwards

    Live Collection

    renew()

    Indicates the SDK to renew the access token without an auth token.

    renewWithAuthToken(...)

    Indicates the SDK to renew the access token with an auth token. (Required for secure login)

    unableToRetrieveAuthToken()

    Indicates the SDK to postpone renewal.

    SDK will re-initiate access token renewal at a later time, but no sooner than 10 minutes.

    Error Handling
    Session State Diagram
    Session Handler
    Mention Users
    Render Mentions

    Realtime Events

    The SDK supports real-time events of various data models through a robust event-driven mechanism. For instance, when a user modifies their profile, these changes can seamlessly be reflected in another user's device. This reflection is achieved via the same Live Objects/Collections that the user is observing in real-time.

    Currently, the SDK supports real-time event subscriptions for the following models:

    • Community

    • Post

    • Comment

    • User

    • Follow/Unfollow

    • Subchannel

    hashtag
    Usage

    To subscribe or unsubscribe from the relevant real-time events, you need to create a Subscription Topic. Upon constructing the subscription topic, the SDK exposes methods for subscribing and unsubscribing, allowing you to listen to specific events without needing to create a new topic.

    hashtag
    Construct Subscription Topic

    The subscription topic construction, excluding Follow/Unfollow topics, requires two parameters:

    1. Data Model (required): This represents the model to which we wish to subscribe, which can be any model.

    2. Subscription Level (optional): This allows specifying the event level within that model for real-time updates. The SDK includes an enum for this purpose. If not provided, the default subscription level corresponds to the passed model type.

    hashtag
    Observe updates

    Once you've successfully established a subscription using the methods outlined previously, the SDK will start receiving data pertaining to the events you've subscribed to. Should there be any alterations to the you are observing, you will be notified via the observer block of the respective Live Object or Live Collection. This functionality ensures you always have access to the most current data without needing to manually fetch updates.

    Here's an example of subscribing to real-time events from a subscription topic and observing changes via a live object. For available topics please visit and .

    In JavaScript SDK, After subscribing to data models from liveObjects, the changes from the realtime event will also be reflected on the dataUpdated event of the same liveObject.

    Available event handlers:

    • onCommunityCreated

    hashtag
    Unsubscribe Events

    To ensure the number of active subscriptions stays within the limit, it is recommended to unsubscribe from topics when they are no longer needed. This could mean unsubscribing when leaving a particular screen or during periods of inactivity.

    Each topic subscription in the SDK provides an unsubscribe method. For unsubscribing, use the Unsubscribe topic method.

    If the logout() method is invoked at any point, the current session will be terminated and all existing subscriptions will be automatically removed. This functionality assists in efficiently managing active subscriptions and preventing unwanted data consumption.

    Use unsubscribeTopic(...) method from AmityTopicSubscription class or use unsubscribeEvent(:_) method from the model itself

    Supported ✅ (please wait while we prepare a real example!)

    By adopting these practices, you can efficiently manage the subscription limit and maintain a responsive and performant application.

    hashtag
    Subscription Topics limit

    The SDK imposes a maximum limit of 20 for the number of topics that can be subscribed to simultaneously. Developers are advised to manage their list of subscriptions and unsubscribe as necessary.

    For instance, suppose you have two screens: one displays a list of communities, and the other displays community details. You may want to subscribe when a user is viewing community details and unsubscribe when the user returns to the community list screen.

    Even if you subscribe to the same topic and event multiple times, the SDK maintains only one subscription.

    hashtag
    Strategies for Managing Subscription Limit

    1. Use higher-level topics: Instead of creating a topic for each post within a community or each comment within a post, it's recommended to create a single community topic for all posts and comments within that community. This can be achieved by using the getCommunityTopic method with a SubscriptionLevel of POST_AND_COMMENT.

    2. Subscribe when rendered, unsubscribe when not: Developers should consider subscribing to a topic when a liveObject is rendered and unsubscribing when it's no longer needed. For instance, if you have a list of communities on a page and you navigate to a page showing a community's details, you may want to subscribe when the user is viewing community details and unsubscribe when the user returns to the community list page.

    TypeScript Live Objects/Collections

    In the Amity TypeScript SDK, we have the concept of Live Object and Live Collection.

    Live Object is represented by an instance of Amity Object. It helps to observe changes in a single object.

    Live Collection is represented by an instance of Amity LiveCollection. It helps to observe changes in a list of objects.

    For example: Amity.Post or Amity.LiveCollection<Amity.Post>

    SDK handles lots of data received from various sources. Data can be present in local cache. It may also be queried from the server or received from real-time event. What this means is that the same data is constantly updating. The data that you are accessing at the moment can get updated and become out of sync.

    Live Object and Live Collection helps in syncing data so you will always get the most recent one. New data gets automatically collected everytime when there is an update and user need not refresh to get the recent data.

    Live Collection is available for the following in user/community feeds:

    • Post Collection

    • Comment Collection

    • Reactions Collection

    circle-info

    Live Collection is not supported for global feed and custom post ranking.

    hashtag
    Live Object

    Although live objects were introduced prior to v6. All getter methods for singular objects (example getPost) will now return a subscribe-able object.

    This means that if an object gets updated and you have subscribed to real time events, the object will get updated automatically via real time events.

    If for your use case you don't require any real time updates, you can unsubscribe immediately. For further information about Live Object, please visit page.

    hashtag
    Getting Real Time Updates for an Object

    hashtag
    Getting the object only once

    hashtag
    Live Collection

    Although live collections were introduced prior to v6. All query methods for collection of objects (example getPosts) will now return a subscribe-able collection.

    This means that if an object in the collection gets updated and you have subscribed to real time events, the collection will get updated automatically via real time events.

    If for your use case you don't require any real time updates, you can unsubscribe immediately. Similar to live objects above. For further information about Live Collection, please visit page.

    hashtag
    Getting Real Time updates for a collection

    hashtag
    Getting paginated collection without and real time updates

    Javascript Live Objects/Collections

    All data returned by the SDK are wrapped in the SDK's LiveObject API. The LiveObject API allows you to easily retrieve the queried data asynchronously, as well as subscribe to any new changes to the data.

    hashtag
    LiveObject

    Observing live changes to any object queries can be done by observing the dataUpdated event on the Live Object:

    In this example, the block observes the data of the currently authenticated user and prints out the displayName. The observe block can be called multiple times throughout the lifetime of the application:

    • If the requested object data is stored locally on the device, the block will be called immediately with the local version of the data (you can verify this through the dataStatus property).

    • In parallel, a network request for the latest version of the data is fired. Once the network returns the data, the observe block will be called again with the updated data.

    • Any future changes to the data (whenever the user changes its

    We recommend you to always call removeAllListeners() whenever you are done observing an event to avoid any unnecessary callbacks.

    hashtag
    Model

    The data provided by LiveObject is directly accessible via the model property. The model property is always kept up to date with the latest state changes; wheneverdataUpdated event is fired, the model property has already been updated.

    hashtag
    Data Status

    If you want to exclusively display fresh data in your UI (without using the potientially out-of-date local data), you can do so by reading the object's dataStatus property, which reflects the status of the callback data, and check that its value is set to fresh.

    You can also use the object's loadingStatus property to determine the current state of network operations being performed by the LiveObject. This is useful for any UI element that needs to provide the loading state.

    The LiveObject can also emit events for updates for dataStatus as well as loadingStatus. As with other events, please make sure to call removeAllListeners() when you are done observing changes to these values in order to prevent memory leaks.

    hashtag
    Events Order

    The LiveObject updates statuses and data in strict order and emits related events accordingly when an instance is created. Few different cases might occurs when you create a LiveObject instance:

    hashtag
    Data is not cached.

    Initial values:

    • loadingStatus = LoadingStatus.Loading

    • dataStatus = DataStatus.NotExist

    • model = undefined

    Process received data:

    • emits loadingStatusChanged

    • emits dataStatusChanged

    • emits dataUpdated

    hashtag
    Data is cached, but is not fresh.

    Initial values:

    • loadingStatus = LoadingStatus.Loading

    • dataStatus = DataStatus.Local

    • model = localData

    Process received data (same order):

    • emits loadingStatusChanged

    • emits dataStatusChanged

    • emits dataUpdated

    hashtag
    Data is cached and is fresh.

    • loadingStatus = LoadingStatus.Loaded

    • dataStatus = DataStatus.Fresh

    • model = localFreshData

    hashtag
    Interface

    This is the list of LiveObject members and methods.

    Members

    • model = model that the live object should fetch

    • loadingStatus = determine the current state of network operations being performed by the LiveObject

    • dataStatus =

    Methods

    • on(event, callback) = listens to event and executes callback when event is fired

    • once= same as the on

    hashtag
    Get Post data

    Here is a sample code on how the get Post data.

    hashtag
    LiveCollection

    The LiveObject API supports queries that return a list of objects, this is known as a LiveCollection. LiveCollection has the same methods and properties as its object counterpart, but contains a few other helper methods around pagination.

    hashtag
    Pagination

    Pagination with LiveCollections is very simple: the collection offers a convenient nextPage method that you can call which will automatically trigger a local cache lookup, a network call, and multiple LiveObject updates once new data is returned. Every collection starts with one page of 20 models. After nextPage() is successful, the dataUpdated event will be triggered with a new array combining both the old objects as well as 20 newly fetched objects.

    The dataUpdated event will be dispatched when the first set of data from the server is loaded. Calling nextPage will load the next set of data. Once all data are loaded, the dataUpdated event will once again be dispatched.

    You can use the nextPage property to determine if you've scrolled to the end of the list. The nextPage property initially returns false until the first collection query is finished.

    Lastly, if there is a need to shrink the list of objects exported back to only the first 20 records (for example, if you pass the LiveCollection object to a new view), you can simply call resetPage().

    hashtag
    Models

    Similar to model property of the LiveObject, the LiveCollection provides models property what is basically is an array of LiveObject's model objects. models is mutable and always contains same data as one what returned by dataUpdated event.

    hashtag
    Errors

    Both LiveObject and LiveCollection can be subscribed to the dataError event which is fired every time an error happens during the data update process. In other words, every time the LiveObject or LiveCollection fails to get data from the server - this error will be emitted.

    hashtag
    Dispose LiveObject and LiveCollection

    We recommend you to always call dispose() whenever you are done working with any LiveObject/LiveCollection.

    Dispose is a very important functionality of the LiveObject. It allows you to avoid memory leaks and keeps your application performant. What does dispose() do:

    • unsubscribe all listeners attached to the LiveObject instance;

    • stop all internall observers related to the LiveObject instance;

    • clean up an internall buffer of the LiveObject instance;

    After you call dispose() on a LiveObject instance, dataStatus and loadingStatus switch to Error.

    Audio Message

    hashtag
    Send an Audio Message

    An audio message is a type of message that allows users to send and receive audio recordings in a chat or messaging application. Audio messages can be used to convey emotions, tone, or detailed information in a way that is not always possible with text messages or other types of media. They are a convenient and intuitive way to communicate with other users in real-time.

    With the Amity Chat SDK, you can easily send and receive audio messages within your chat or messaging application. Simply provide the local path of the audio file to the sendAudioMessage method.

    Here is a brief explanation of the function parameters:

    • text/caption: A string that contains the text message that the user wants to send. This parameter is mandatory as it contains the actual message content.

    • attachment: The local audio path that the user wants to send on the device

    Version 6

    Version 5 (Maintained)

    Version 6

    Version 5 (Maintained)

    Sending audio messages uses the same steps as sending a file message. Refer to page for more details.

    circle-exclamation

    Supported audio formats are MP3, WAV and cannot exceed 1GB in size

    import { FileRepository, MessageRepository } from '@amityco/js-sdk';
    
    // this function takes in input a File from a <input type="file" />
    const createImageMessage = (file: File) => {
      // first, create the file object.
      const liveFile = FileRepository.createFile({ file })
    
      // second, create the message object with the fileId from the liveFile
      const liveMessage = MessageRepository.createImageMessage({
        channelId: 'my-channel',
        imageId: liveFile.model.fileId,
        caption: 'have a look!',
        tags: ['tag1', 'tag2'],
      })
    }ja
    import { UserRepository } from '@amityco/js-sdk';
    const userRepo = new UserRepository();
    import { useState, useEffect, useMemo } from 'react'
    
    // our image component
    const FileImage = ({ fileId }) => {
      const [fileUrl, setFileUrl] = useState()
    
      useEffect(() => {
        const liveObject = FileRepository.fileInformationForId(fileId)
    
        liveObject.on('dataUpdated', model => setFileUrl(model.fileUrl))
        liveObject.model && setFileUrl(liveObject.model.fileUrl)
    
        return () => {
          liveObject.dispose()
        }
      }, [fileId])
    
      return fileUrl ? <img src={fileUrl} /> : null
    }
    
    // our user component
    const UserHeader = ({ userId }) => {
      const [user, setUser] = useState({})
    
      const displayName = useMemo(
        () => user?.displayName ?? user?.userId,
        [user],
      )
    
      useEffect(() => {
        const liveObject = UserRepository.getUser(userId)
    
        liveObject.on('dataUpdated', setUser)
        liveObject.model && setUser(liveObject.model)
    
        return () => {
          liveObject.dispose()
        }
      }, [userId])
    
      return (
        <div>
         {user.avatarFileId && <FileImage fileId={user.avatarFileId} />}
         {user.avatarCustomUrl && <img src={user.avatarCustomUrl} />}
        </div>
      )
    } 
    const myMetadata = { whatever: “i want”, toPass: “is ok” }
    
    const success = await amityClient.updateCurrentUser({
      displayName: "Batman",
      description : "Hero that Gotham needs",
      metadata: myMetadata,
    })
    import { getCommunityTopic, SubscriptionLevels } from '@amityco/js-sdk';
    
    // Community topic to subscribe to all events of that community model only
    // Example events: community joined, community left, community updated 
    const topic = getCommunityTopic(communityModel, SubscriptionLevels.COMMUNTIY);
    
    // Community topic to subscribe to all post events of that community model
    // Example events: post created, post deleted, post updated
    const topic = getCommunityTopic(communityModel, SubscriptionLevels.POST);
    
    // Community topic to subscribe to all comment events of that community model
    // Example events: comment created, comment deleted, comment updated
    const topic = getCommunityTopic(communityModel, SubscriptionLevels.COMMENT);
    
    // Community topic to subscribe to all posts and comment events of that community model
    // Example events: comment created, comment deleted, comment updated
    const topic = getCommunityTopic(communityModel, SubscriptionLevels.POST_AND_COMMENT);
    import { getPostTopic, SubscriptionLevels } from '@amityco/js-sdk';
    
    // Post topic to subscribe to all events of that post model only
    // Example events: post edited, reactions added 
    const topic = getPostTopic(postModel, SubscriptionLevels.POST);
    
    // Post topic to subscribe to all comment events of that post model
    // Example events: comment created, comment deleted, comment updated
    const topic = getPostTopic(postModel, SubscriptionLevels.COMMENT);
    import { getCommentTopic, SubscriptionLevels } from '@amityco/js-sdk';
    
    // Comment topic to subscribe to all comment events of that post model
    // Example events: comment created, comment deleted, comment updated
    const topic = getCommentTopic(commentModel, SubscriptionLevels.COMMENT);
    import { getUserTopic, SubscriptionLevels } from '@amityco/js-sdk';
    
    // User topic to subscribe to all events of that user model only
    const topic = getUserTopic(userModel, SubscriptionLevels.USER);
    
    // User topic to subscribe to all post events of that user model
    // Example events: post created, post deleted, post updated
    const topic = getUserTopic(userModel, SubscriptionLevels.POST);
    
    // User topic to subscribe to all comment events of that user model
    // Example events: comment created, comment deleted, comment updated
    const topic = getUserTopic(userModel, SubscriptionLevels.COMMENT);
    
    // User topic to subscribe to all posts and comment events of that user model
    // Example events: comment created, comment deleted, comment updated
    const topic = getUserTopic(userModel, SubscriptionLevels.POST_AND_COMMENT);
    https://github.com/AmityCo/Amity-Social-Cloud-SDK-iOS-SwiftPM
    binary "https://raw.githubusercontent.com/AmityCo/Amity-Social-Cloud-SDK-iOS/master/AmitySDK.json" ~> 5.3.0 
    platform :ios, '12.0'
    
    use_frameworks!
    
    pod 'AmitySDK'
    https://github.com/AmityCo/Amity-Social-Cloud-SDK-iOS-VideoBroadcast-SwiftPM
    import AmityLiveVideoBroadcastKit
    https://github.com/AmityCo/Amity-Social-Cloud-SDK-iOS-VideoPlayer-SwiftPM
    import AmityVideoPlayerKit
    // Example of a Swift file which contains a class to interact with AmitySDK.
    
    @objc class SDKLoginManager: NSObject {
        
        let client: AmityClient?
        
        @objc init(apiKey: String) {
            self.client = try? AmityClient(apiKey: apiKey)
        }
        
        @objc func login(userId: String, displayName: String, authToken: String, completion: @escaping (Bool, Error?) -> Void) {
            self.client?.login(userId: userId, displayName: displayName, authToken: authToken, completion: completion)
        }
    }
    #import "ViewController.h"
    #import "YourProjectName-Swift.h" // <- This import exposes above Swift file to your Objc project.
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view.
    }
    
    - (void)testSDKUsage {
    
        SDKLoginManager *loginManager = [[SDKLoginManager alloc] initWithApiKey:@"my-api-key"];
        [loginManager loginWithUserId:@"user-id" displayName:@"display-name" authToken:@"auth-token" completion:^(BOOL isSuccess, NSError * _Nullable error) {
            
            // Handle login completion here
        }];
    }
    
    @end
    import { FileRepository, LoadingStatus } from '@amityco/js-sdk';
    
    const liveObject = FileRepository.createFile({ 
      file, // https://developer.mozilla.org/en-US/docs/Web/API/File
      onProgress: ({ currentFile, currentPercent }) => {
      },
    });
    
    liveObject.on('loadingStatusChanged', ({ newValue }) => {
      if (newValue === LoadingStatus.Loaded) {
        console.log('The file is uploaded', liveObject.model);
      }
    });
    
    liveObject.on('dataError', (error) => {
      console.error('can not upload the file', error);
    });
    
    // upload video
    const liveObject = FileRepository.createVideo({ 
      file,
      onProgress: ({ currentFile, currentPercent }) => {
      },
    });
    Refer to the 
    file model
     for the description of the response after a successful file creation. If an error is encountered while creating the file, it will return the following errors:
    //Attached file payload is too large
    {
      "status": "error",
      "code": 500000,
      "message": "Payload too large."
    }
    
    // Unexpected error
    {
      "status": "error",
      "code": 500000,
      "message": "Unexpected error"
    }
    import { FileRepository } from '@amityco/js-sdk';
    
    let file;
    const liveObject = FileRepository.getFile(fileId);
    
    liveObject.on('dataUpdated', (updatedModel) => {
      file = updatedModel;
    });
    
    liveObject.on('dataError', (error) => {
      console.error('Can not get the file', error);
    });
    
    file = liveObject.model;
    import { FileRepository } from '@amityco/js-sdk';
    
    const success = await FileRepository.deleteFile(fileId);
    "data": {
        "success": true
      }
    //Attached file payload is too large
    {
      "status": "error",
      "code": 500000,
      "message": "Payload too large."
    }
    
    // Unexpected error
    {
      "status": "error",
      "code": 500000,
      "message": "Unexpected error"
    }
    let fileRepository = AmityFileRepository(client: client)
        ...
        
        func downloadVideoThumbnailAsData(from message: AmityMessage) {
            guard let thumbnailFileId = message.data?["thumbnailFileId"] as? String,
                  !thumbnailFileId.isEmpty,
                  let imageInfo = message.getVideoThumbnailImageInfo() else { return }
            
            
            // Download from url and return saved image url.
            fileRepository.downloadImage(fromURL: imageInfo.fileURL, size: .small) { imageUrl, error in
                // Handle image url and error.
            }
        }
        
        func downloadVideoThumbnailAsUIImage(from message: AmityMessage) {
            guard let thumbnailFileId = message.data?["thumbnailFileId"] as? String,
                  !thumbnailFileId.isEmpty,
                  let imageInfo = message.getVideoThumbnailImageInfo() else { return }
            
            // Download from url and return image.
            fileRepository.downloadImageAsData(fromURL: imageInfo.fileURL, size: .small) { image, size, error in
                // Handle image and error.
            }
        }
    // add 'user1' and 'user2' to this channel
    const isAdded = await ChannelRepository.addMembers({
      channelId: 'channel1',
      userIds: [ 'user1', 'user2' ],
    });
    
    // remove 'user3' from this channel
    const isRemoved = await ChannelRepository.removeMembers({
      channelId: 'channelId',
      userIds: [ 'user3' ],
    });
    
    // leave this channel
    const isLeaved = await ChannelRepository.leave('channelId');
    const isBanned = await ChannelRepository.banMembers({ 
      channelId: 'channel1', 
      userIds: ['user1']
    );
    ​
    const isUnbanned = await ChannelRepository.banMembers({ 
      channelId: 'channel1', 
      userIds: ['user1']
    );
    ​
    await ChannelRepository.addRole({ 
      channelId: 'channel1', 
      userIds: ['user1'],
      role: 'role1',
    );
    ​
    await ChannelRepository.removeRole({ 
      channelId: 'channel1', 
      userIds: ['user1'],
      role: 'role1',
    );
    import { MessageRepository } from '@amityco/js-sdk';
    ​
    const liveCollection = MessageRepository.queryMessages({
      channelId: 'channelId',
      parentId: parentIdValue,
      filterByParentId: true,
      tags: ['summer2021']
      excludeTags: ['awful_hotel']
    });
    import { MessageRepository } from '@amityco/js-sdk';
    
    const liveCollection = MessageRepository.queryMessages({
      channelId: 'channel1',
      parentId: 'exampleParentMessageId',
      filterByParentId: true,
    });
    import { MentionType, MessageRepository, MessageTools } from '@amityco/js-sdk';
    
    MessageRepository.createTextMessage({
      channelId: 'channelId',
      text: 'hi @user1 @user2',
      mentionees: [{ type: MentionType.User, userIds: ['userId1', 'userId2'] }],
      metadata: MessageTools.createMentionMetadata([
        { type: MentionType.User, userId: 'userId1', index: 3, length: 5 },
        { type: MentionType.User, userId: 'userId2', index: 10, length: 5 },
      ]),
    });
    import { MentionType, MessageRepository, MessageTools } from '@amityco/js-sdk';
    
    MessageRepository.createTextMessage({
      channelId: 'channelId',
      text: 'hi @all',
      mentionees: [{ type: MentionType.Channel }],
      metadata: MessageTools.createMentionMetadata([
        { type: MentionType.Channel, index: 3, length: 3 },
      ]),
    });
    import { MentionType, MessageRepository, MessageTools } from '@amityco/js-sdk';
    
    MessageRepository.updateMessage({
      messageId: 'messageId',
      data: { text: 'hi @user3' },
      mentionees: [{ type: MentionType.User, userIds: ['userId3'] }],
      metadata: MessageTools.createMentionMetadata([{ type: MentionType.User, userId: 'userId3', index: 3, length: 5 }]),
    });
    // observe data changes
    const currentUser = client.currentUser;
    
    currentUser.on('dataUpdated', model => {
      console.log(`Current user is: ${model.displayName}`);
    })
    
    // unobserve data changes once you are finished
    currentUser.removeAllListeners('dataUpdated');
    image-text
    image-text
    Followers/Following Collection
  • Channel Collection

  • Message Collection

  • Channel Member Collection

  • Community Collection

  • Community Category Collection

  • Community Objects

  • Community Members Collection

  • Live Object
    Live Collection
    displayName
    on another device, for example) can trigger additional callbacks.
    - only if data is really different
    reflects the status of the callback data
    method but can only be called once
  • removeAllListeners = removes all listeners from on

  • dispose = causes the LiveObject to be destroyed and cleaned up

  • import { PostRepository, subscribeTopic, getPostTopic } from '@amityco/ts-sdk';
    import { FC, useEffect, useState } from 'react';
    
    const disposer: Amity.Unsubscriber[] = [];
    
    const GetPost: FC<{ postId: string }> = ({ postId }) => {
      const [post, setPost] = useState<Amity.Post>();
    
      useEffect(() => {
    
        const unsubscribePost = PostRepository.getPost(postId, ({ data }) => {
         const { post, loading, error } = data
         
         if (post) {
           /*
           * This step is important if you wish to recieve real time updates
           * Here, you are letting the server know that you wish to recieve real time
           * updates regarding this post
           */
           disposers.push(subscribeTopic(getPostTopic(post)))
           
           setPost(post)
         }
        });
        
        disposers.push(unsubscribePost);
      }, [postId]);
    
      return null;
    };
    import { PostRepository } from '@amityco/ts-sdk';
    import { FC, useEffect, useState } from 'react';
    
    const GetPostOnce: FC<{ postId: string }> = ({ postId }) => {
      const [post, setPost] = useState<Amity.Post>();
    
      useEffect(() => {
        const unsubscribePost = PostRepository.getPost(postId, ({ data }) => {
         const { post, loading, error } = data
         
         if (post) {       
           setPost(post)
         }
        });
        
        unsubscribePost()
      }, [postId]);
    
      return null;
    };
    import {
      PostRepository,
      subscribeTopic,
      getUserTopic,
      getCommunityTopic,
      SubscriptionLevels,
    } from '@amityco/ts-sdk';
    import { FC, useEffect, useState } from 'react';
    
    const disposers: Amity.Unsubscriber[] = [];
    
    const GetPosts: FC<{ targetId: string; targetType: string }> = 
    ({ targetId, targetType }) => {
      const [posts, setPosts] = useState<Amity.Post[]>();
    
      useEffect(() => {
        const unsubscribe = PostRepository.getPosts(
          { targetId, targetType },
          ({ data: posts, onNextPage, hasNextPage, loading, error }) => {
            setPosts(posts);
            /*
             * this is only required if you want real time updates for each
             * post in the collection
             */
            subscribePostTopic(targetType, targetId);
          },
        );
    
        disposers.push(unsubscribe);
    
        return () => {
          disposers.forEach(fn => fn());
        };
      });
    
      return null;
    };
    
    const subscribePostTopic = (targetType: string, targetId: string) => {
      if (isSubscribed) return;
    
      if (targetType === 'user') {
        const user = {} as Amity.User; // use getUser to get user by targetId
        disposers.push(
          subscribeTopic(getUserTopic(user, SubscriptionLevels.POST), () => {
            // use callback to handle errors with event subscription
          }),
        );
        return;
      }
    
      if (targetType === 'community') {
        // use getCommunity to get community by targetId
        const community = {} as Amity.Community; 
        disposers.push(
          subscribeTopic(getCommunityTopic(community, SubscriptionLevels.POST), () => {
            // use callback to handle errors with event subscription
          }),
        );
      }
    };
    
    import {
      PostRepository,
      subscribeTopic,
      getUserTopic,
      getCommunityTopic,
      SubscriptionLevels,
    } from '@amityco/ts-sdk';
    import { FC, useEffect, useState } from 'react';
    
    const GetPosts: FC<{ targetId: string; targetType: string }> = 
    ({ targetId, targetType }) => {
      const [posts, setPosts] = useState<Amity.Post[]>();
    
      useEffect(() => {
        const unsubscribe = PostRepository.getPosts(
          { targetId, targetType },
          ({ data: posts, onNextPage, hasNextPage, loading, error }) => {
            if (posts)
              setPosts(posts);
            
            // to get next page use onNextPage()
          },
        );
    
        unsubscribe()
      });
    
      return null;
    };
    import { LoadingStatus, DataStatus } from '@amityco/js-sdk';
    
    if (currentUser.dataStatus === DataStatus.Fresh) {
      // the data field of this object is up to date
      console.log(currentUser.model);
    }
    if (currentUser.loadingStatus === LoadingStatus.Loading) {
      // this object is current loading, show loading UI
    }
    currentUser.on('dataStatusChanged', callback);
    currentUser.on('loadingStatusChanged', callback);
    const livePost = PostRepository.getPost(postId)
    console.log(livePost.model)
    import { MessageRepository } from '@amityco/js-sdk';
    
    const messageRepo = new MessageRepository('channel1');
    const messages = messageRepo.messagesForChannel({ channelId: 'channel1234' });
    messages.on('dataUpdated', models => {
      // models will be an array of message objects
      models.forEach(message => {
        console.log('Message: ', message);
      });
    });
    const liveCollection = MessageRepository.queryMessages({
        channelId: 'channelId',
        type: 'text'
    });
    
    liveCollection.on(“dataUpdated”, messages => console.log(messages))
    
    const loadMore = () => {
      if (liveCollection.nextPage) {
        liveCollection.nextPage();
      }
    };
    const messages = messageRepo.messagesForChannel({ channelId: 'channel1234' });
    
    messages.on('dataError', error => {
      // Every error has a code. You can control how your application should behave in response to the error.
      if (error.code !== YYYYYY) {
        throw error;
      }
    });
    // create an user LiveObject and a messages LiveCollection when you mount your component or view
    const currentUser = client.currentUser;
    const messages = messageRepo.messagesForChannel({ channelId: 'channel1234' });
    
    ...
    
    // before leaving page, unmounting component etc
    currentUser.dispose();
    messages.dispose();
    for file messages
  • AmityMessage.DataType.AUDIO for audio messages

  • AmityMessage.DataType.VIDEO for video messages

  • AmityMessage.DataType.CUSTOM for custom messages

  • onCommunityUpdated

  • onCommunityDeleted

  • onCommunityJoined

  • onCommunityLeft

  • onCommunityUserAdded

  • onCommunityUserBanned

  • onCommunityUserRemoved

  • onCommunityUserUnbanned

  • onPostCreated

  • onPostUpdated

  • onPostDeleted

  • onPostApproved

  • onPostDeclined

  • onPostFlagged

  • onPostUnflagged

  • onPostReactionAdded

  • onPostReactionRemoved

  • onCommentCreated

  • onCommentUpdated

  • onCommentDeleted

  • onCommentFlagged

  • onCommentUnflagged

  • onCommentReactionAdded

  • onCommentReactionRemoved

  • onUserFollowed

  • onUserUnfollowed

  • onFollowerRequested

  • onFollowRequestAccepted

  • onFollowRequestCanceled

  • onFollowRequestDeclined

  • onFollowerDeleted

  • onFollowInfoUpdated

  • Live Objects/Collections
    Social Realtime Events
    Chat Realtime Events
    Live Object
    subchannelId
    : An identifier for the subchannel where the message will be sent. Subchannels are subdivisions within a channel that represent individual topics or chat threads. Messages and interactions occur within subchannels, not the main channel itself.
  • tags - Arbitrary strings that can be used for defining and querying for the messages.

  • File Message

    720p - 1280×720 horizontal, and 720x1280 in vertical

  • 480p - 640x480 horizontal, and 480x640 in vertical

  • 360p - 480x360 horizontal, and 360x480 in vertical

  • (All transcoded videos are in MP4 format)

    transcoded - the video is transcoded and the resolutions are provided to videoUrl
  • error - the video encounters an issue while transcoding

  • Date/time when a file is updated

    attributes

    Information about the file

    SDK, Console

    Live

    Only joined and invited members and admins

    Members and admins

    All Moderation tools

    SDK, Console

    Broadcast

    All members and admins

    Admins

    Admin Moderation tools (ASC Console)

    Console

    Conservation

    All members and admins

    Members

    No moderation tools

    SDK

    When message attachment is being uploaded to server

    syncing

    uploading

    When message is synced successfully with the server

    synced

    synced

    When message syncing failed

    error

    error

    Posts

    Here's an overview of posts and how you can get started with integrating them into your applications

    A post can be defined as a piece of content created and shared by a user within a network or community. The post can include various types of information such as text, images, videos, links, or other multimedia elements. The SDK provides the necessary tools and functionality for users to create, view, and interact with posts in a social feed. Posts can be displayed in chronological order and can be customized and configured using various settings and options provided by the SDK. The purpose of a post in a product context is to allow users to share information, express thoughts, or connect with others within a social network or community using the SDK.

    Amity supports a wide range of post types, each with its own unique set of features and capabilities. The types of posts that you can create in Amity include text, image, video, file, live stream, poll, and custom posts. Furthermore, a post supports real-time events and Live Object features, for more information please refer to Live Objects/Collections and Realtime Events

    hashtag
    Post Structure

    The post structure is a parent-child relationship, with the parent post serving as a container for text data, for other post types such as images or videos, while each individual image or video is treated as a separate child post. To illustrate this, let's take the example of an image post with two images. In this case, there would be one parent post serving as a text container, and two child posts, each containing one of the images.

    In addition to enabling users to create more dynamic and engaging content, both parent and child posts also support reactions and comments. This means that users can interact with not only the parent post but also with each individual child post, providing a more comprehensive and engaging way to engage with content.

    hashtag
    Post Repository

    The functionality of posts can be utilized through the Post Repository, which offers methods for interacting with a data source that stores posts. This includes methods for obtaining a specific post, creating a new post, updating an existing post, or deleting a post.

    Supported ✅ (Please wait while we prepare a real example!)

    hashtag
    Post Description

    Poll

    The Amity Social SDK encompasses comprehensive support for polls, offering developers an effortless way to incorporate polls into their social applications. Polls enable users to create and participate in a diverse range of topics, sparking targeted engagement and conversations among users.

    To integrate poll functionality, developers can utilize the poll features offered by the Amity Social SDK in their applications. Polls can be tailored to meet specific needs, including options for single or multiple-choice polls, setting poll expiration dates, and more. Users can then participate in the poll by choosing their preferred option. At present, the Amity Social SDK only supports the integration of polls within posts, please refer to - , .

    hashtag
    Create Poll

    As demonstrated in the code sample below, here's a way to create a poll in the poll post.

    Polls can be created with the following settable controls:

    • question - A question that can be up to 500 characters long.

    • answer - A set of two to ten answers. Each answer can be up to 200 characters long.

    • answerType

    hashtag
    Vote Poll

    This function enables you to cast a single vote and the vote cannot be revoked. If the poll type is multiple, you have the option to select multiple choices.

    Here's an explanation of the method's parameters:

    • pollId: This is a required parameter of type String, which represents the ID of the poll that the user wants to vote on.

    • answerIds: This is a required parameter of type Array<String>, which represents an array of IDs of the answer options that the user wants to vote for. Users can select one or multiple answers depending on the poll's configuration.

    hashtag
    Close Poll

    The ability to close a poll is restricted exclusively to individuals who have ownership permissions, such as the creator of the poll or an administrator. It is important to note that a poll can only be closed prior to its designated closing time.

    Here's an explanation of the method's parameter:

    • pollId: This is a required parameter of type String, which represents the ID of the poll that the user wants to close.

    hashtag
    Delete Poll

    The deletion of a poll is limited exclusively to individuals who possess ownership permissions, such as the creator of the poll or an administrator.

    Here's an explanation of the method's parameter:

    • pollId: This is a required parameter of type String, which represents the ID of the poll that the user wants to delete.

    Supported ✅ (Please wait while we prepare a real example!)

    Video
    const [community, setCommunity] = React.useState();
    
    React.useEffect(() => {
      const liveObject = CommunityRepository.communityForId('communityId');
    
    	// The realtime event for any changes to the community will also reflect here. 
      liveObject.on('dataUpdated', setCommunity);
    
      return () => liveObject.dispose();
    }, []);
    
    React.useEffect(() => {
      if (community.communityId) {
    		let topic = getCommunityTopic(community, SubscriptionLevels.COMMUNITY);
        EventSubscriberRepository.subscribe(topic);
       
        return EventSubscriberRepository.unsubscribe(topic);
      }
    }, [community.communityId]);
    import { 
    	getCommunityTopic,
    	EventSubscriberRepository,
    	SubscriptionLevels } from '@amityco/js-sdk';
    
    let topic = getCommunityTopic(communityModel, SubscriptionLevels.POST);
    
    // Subscription has an optional error callback parameter that can be used.
    EventSubscriberRepository.subscribe(topic, (err) => {
    	if (err) { // handle subscription error here}
    	// handle subscription success here.
    });
    
    // Unsubscribe
    EventSubscriberRepository.unsubscribe(topic);
    //Permission denied error
    {
      "status": "error",
      "code": 400301,
      "message": "Permission denied"
    }
    
    Resource Not Found error
    {
      "status": "error",
      "code": 400400,
      "message": "Resource Not Found."
    }
    
    //Passed the wrong parameters error
    {
      "status": "error",
      "code": 500000,
      "message": "Parameters error."
    }

    postedUserId

    String

    ID of the user who posted

    sharedUserId

    String

    ID of the user who shared the post

    SharedCount

    Integer

    Number of times the post is shared

    targetID

    String

    ID of the target

    targetType

    String

    Type of target

    dataType

    String

    Data type of post

    data

    Object

    Data of the post

    metadata

    Object

    Metadata of the post

    flagCount

    Integer

    Number of times that the post is flagged

    editedAt

    Date

    Date/time the post was edited

    createdAt

    Date

    Date/time the post was created

    updatedAt

    Date

    Date/time the post was updated

    reactions

    Object

    Information about the post reactions

    reactionsCount

    Integer

    Number of reactions to the post

    myReactions

    Array<String>

    Reactions to the post

    commentsCount

    Integer

    Number of comments to the post

    comments

    Array<AmityComment>

    The first three comments of the post for previewing purpose

    childrenPosts

    Object

    Children posts

    isDeleted

    Boolean

    Flag that indicates if the post is deleted. True means post is already deleted.

    hasFlaggedComment

    Boolean

    Flag that indicates if the post has flagged comments. True means it has.

    hasFlaggedChildren

    Boolean

    Flag that indicates if the post has flagged children. True means it has.

    tags

    Array<String>

    Arbitrary strings that can be used for defining and querying for the posts in community and user feeds.

    feedId

    String

    ID of the post's feed

    Name

    Data Type

    Description

    postId

    String

    ID of the post

    parentPostId

    String

    ID of the parent post, this can be null if the post is a parent post.

    - Indicates whether the survey allows multiple choices. The available options are
    Single
    (default) and
    Multiple
    .
  • timeToClosePoll - A time window limiting how long the poll will be open. By default, the setTimeToClosePoll value is set to 30 days if no value has been set for it.

  • A simple session handler
    Implement app navigation based on session state
    An example of access token renewal with auth token.
    Observe Session State
    Update the current user avatar
    Update user custom avatar
    Update the current user data
    Upload an image with AmityFileRepository

    Error Handling

    hashtag
    Server Errors

    import { PostRepository } from '@amityco/js-sdk';
    closePoll = async (pollId: string) => Promise<any>
    image-text
    image-text
    image-text
    Channel and Subchannel Structure

    BadRequestError

    Request contains invalid parameters.

    400001

    InvalidRegularExpression

    An invalid regex rule retrieved from or added to the Blocklist

    400002

    VideoFormatInvalidRequestError

    Video format not supported

    400100

    UnauthorizedError

    Unverified user performs any action that requires access token verification.

    400300

    ForbiddenError

    User performs forbidden action such as uploading a pdf file in an image message.

    400301

    PermissionDenied

    User has no permission to perform the action.

    400302

    UserIsMuted

    A muted user sends a message.

    400303

    ChannelIsMuted

    User sends a message in a muted channel.

    400304

    UserIsBanned

    User accessed a channel or community where he is banned.

    400307

    MaxRepetitionExceed

    User reached the limit of the number of sent messages containing blocklisted words.

    400308

    BanWordFound

    User sends a message that contains a blocklisted word.

    400309

    LinkNotAllowed

    User sends a message that contains link that is not in the Allowlist.

    400311

    RPCRateLimitError

    Web socket rate limit is exceeded.

    400312

    GlobalBanError

    Banned user performs any action.

    400314

    UnsafeContent

    Content moderation system detects unsafe content (eg. nudity).

    400315

    DuplicateEntryError

    Display name of a collection already exists (eg. for your channels or community categories).

    400316

    UserIsUnbanned

    Returned when unbanning a user that is not banned.

    400317

    ForbiddenError

    The only active moderator in a channel/community attempts to leave and there are no other moderators in the group.

    400318

    ForbiddenError

    The only moderator in a channel/community attempts to leave and there are no other members in the group.

    400319

    ForbiddenError

    User changes module and user notification settings but the network notification setting is off.

    400400

    ItemNotFound

    System cannot find any resource matched with the requested condition.

    400900

    Conflict

    System cannot create/update duplicated data.

    500000

    BusinessError

    Uncategorized internal system errors not related to any user input.

    500000

    BusinessError

    Video upload failed

    hashtag
    Client Errors

    Code

    Error Name

    Description

    800000

    Unknown

    Uncategorized errors.

    To debug, refer to the 'error.message' property.

    800110

    InvalidParameter

    hashtag
    Error Objects

    Error objects can be returned to you via LiveObjects, callbacks, or client error delegates. The possible error codes are listed in a public error code enum: each case is named after its error.

    You can convert an Amity Exception into an Amity Error with the following:

    circle-info

    All the errors returned by the iOS SDK come in form of an NSError with domain Amity.

    For any specific errors that's handled in PagingData please visit the web page below to properly handle its errors https://developer.android.com/topic/libraries/architecture/paging/load-state#adapterarrow-up-right

    circle-info

    All the errors returned by the SDK come in form of an Error with domain ASC.

    When an error is returned as a result of an action from your side (e.g. trying to join a channel), the action is considered completed and the SDK will not execute any additional logic.

    hashtag
    Global ban error handling

    A global ban error means that the user is banned from the system resulting in the inability to have a connection with the system. If the user already has a session, the session will be revoked and will be unable to create a new session.

    Code

    Error Name

    Description

    400000

    image-text
    image-text

    iOS Live Objects/Collections

    hashtag
    Live Objects and Live Collections

    In iOS AmitySDK, we have a concept of Live Object and Live Collection. LiveObject is represented by AmityObject instance and LiveCollection is represented by an instance of AmityCollection. These are generic classes which encapsulates any other object and notifies the observer whenever any property of the encapsulated object changes.

    Live Object helps to observe changes in a single object whereas Live Collection helps to observe changes in a list of objects. For example: AmityObject<AmityPost> or AmityCollection<AmityMessage>.

    hashtag
    How it Works

    SDK handles a lot of data received from various sources. Data can be present in local cache. It might also be queried from the server or received from some real-time events. This means, some data is constantly updating. The data that you are accessing at the moment can get updated by other sources and becomes out of sync.

    Live Object and Live Collection helps in syncing these constantly updating data, so you will always get the most recent one. Whenever the data gets updated, you will be notified through helper methods in live object and live collection classes.

    New data gets automatically collected everytime when there is an updation and user need not refresh to get the recent data.

    Live collection is available for the following functionalities in user/community feeds:

    • Post Collection

    • Comment Collection

    • Reactions Collection

    Both AmityObject and AmityCollection provide methods that help to observe changes in objects. The life cycle of observation is tied to its token. As soon as the token is invalidated or deallocated, observation ends.

    hashtag
    AmityNotificationToken

    AmityNotificationToken is a simple object which keeps track of what is being observed. Each observation from Live Object or Live Collection is tied to its respective token. As soon as the token is invalidated or deallocated, observation ends. The token is declared within the scope of the class.

    The token is used in combination with AmityObject or AmityCollection. We will explore it more in AmityObject and AmityCollection concepts.

    hashtag
    AmityObject

    AmityObject is a generic class that keeps track of a single object. It is a live object. In iOS AmitySDK, any object which is encapsulated by AmityObject is a live object.

    Examples:

    • AmityObject<AmityMessage>

    • AmityObject<AmityChannel>

    AmityObject class exposes the following methods:

    • observe

    • observeOnce

    These methods help observe a live object. Whenever any property for observed object changes, the observer is triggered.

    hashtag
    Observer

    observe method can be triggered multiple times throughout the lifetime of the application as long as its associated AmityNotificationToken is retained in memory. observeOnce method, on the other hand, can only be triggered once.

    Both observe and observeOnce methods will be called from the main thread so you can perform any UI update-related tasks from within the observe block itself.

    • If the requested object data is stored locally on the device, the block will be called immediately with the local version of the data. This can be verified through the dataStatus property of AmityObject.

    • In parallel, a request is made to server to fetch the latest version of the data. Once the data is returned, the observe block will be triggered again.

    Lifecycle: The life cycle of the observer is tied to its token. If the token is not retained, then the observer can get deallocated at any time and will not be called. Both observe and observeOnce block will be retained using token as shown below.

    hashtag
    Invalidate token

    The AmityNotificationToken provides a method called invalidate() which can be used to invalidate the token anytime. As soon as you invalidate the token, your observation stops and observe block will no longer be triggered.

    hashtag
    Accessing Objects

    There are multiple ways to access data from AmityObject. AmityObject exposes the following properties:

    • dataStatus: Indicates whether the data is fresh or local

    • loadingStatus: Indicates if the data is being loaded from server or not

    • object

    Once you add an observer block, you can access both local or fresh data as shown below.

    If you want to observe fresh object just once, you can check the data status and invalidate the token once you receive the fresh object.

    For observerOnce method, if data is present locally, this observer will be triggered only once with that local data. If you are looking for fresh data, use the observe block and invalidate the token once fresh data is received as shown above.

    If you only care about local data and do not want to observe anything, you can also access the object property from AmityObject directly.

    While this is possible, we recommend accessing object from within theobserve or observeOnce block depending on your requirement.

    hashtag
    AmityLoadingStatus

    AmityObject can be tracked for their loading status by accessing the loadingStatus property, which is of type AmityLoadingStatus and it can have one of four possible values.

    • 0 (notLoading): Indicates that the data is already fresh locally and does not need to be loaded.

    • 1 (loading): Indicates that the client is currently loading the data from the server.

    • 2 (loaded) - Indicates that the client has successfully loaded fresh data from the server and is up to date.

    hashtag
    AmityCollection

    AmityCollection is a generic class that keeps track of a collection of objects. It is a live collection. In iOS SDK, any object which is encapsulated by AmityCollection class is a live collection.

    Examples:

    • AmityCollection<AmityMessage>

    • AmityCollection<AmityChannel>

    AmityCollection exposes these methods:

    • observe

    • observeOnce

    These methods help to observe a live collection. Whenever any property for any object within the collection changes, the observer is triggered.

    hashtag
    Observer

    observe method can get triggered multiple times throughout the lifetime of the application as long as it's associated AmityNotificationToken is retained in memory. observeOnce, on the other hand, can only be triggered once.

    Both observe and observeOnce method will be called from the main thread so you can perform any UI update related task within the observe block itself.

    • If the requested data collection is stored locally on the device, the block will be called immediately with the local version of the data. This can be verified through the dataStatus property of AmityCollection.

    • In parallel, a request is made to the server to fetch the latest version of the data. Once the data is returned, the observe block will be triggered again.

    Lifecycle: The life cycle of the observer for AmityCollection is also tied to its token. If the token is not retained, the observer can get deallocated at any time and will not be called. So, both observe and observeOnce block should be retained. You can refer to the section in AmityObject about retaining and invalidating a token.

    hashtag
    Accessing Collection

    Unlike most databases, AmityCollection does not return all data in an array. Instead, data is fetched one by one using the objectAtIndex: method. This allows the framework to store most of the actual result on disk, and load them in memory only when necessary.

    AmityCollection also exposes a count property which determines the number of objects present in a collection.

    With these two public interfaces, you can create a robust list UI for your use case. Similar to AmityObject, AmityCollection also exposes dataStatus and loadingStatus property.

    Let's look at the typical flow when accessing a collection data.

    If you want to observe only fresh or local collection, you can access it using thedataStatus property and invalidate the token once you have accessed your desired collection data.

    For observerOnce method, if data is present locally, this observer will be triggered only once with that local data. If you are looking for fresh data, use observe block and invalidate the token once fresh data is received as shown above.

    Observer also provides you with the AmityCollectionChange object which contains indexes of what is added, deleted, or modified in a collection. You can also refer to these properties to update the UI for the list.

    hashtag
    Iterate through collection

    While SDK provides liveCollection.object(at:) to access a single item, you might often find the need to iterate through all objects in the collection. The SDK has a convenient way to do this using .allObjects().

    Using the above method is the same with this logic:

    hashtag
    Pagination

    AmityCollection in SDK returns a maximum of 20 items per page. It has nextPage() and previousPage() method to fetch more data. It also exposes hasNext and hasPrevious property to check if next page or previous page is present.

    Once next page is available, the same observe block gets triggered and you can access the collection as shown above. If you want to shrink the collection to the original first page, you can do so by calling resetPage() method on the same collection.

    One typical usage of Live Collection is in UITableView. Below is an example of fetching a collection and displaying it in a tableview.

    hashtag
    SwiftUI Support

    AmityObject and AmityCollection are now observable object with its properties marked with @Published annotation. Now you can use live object & live collection directly within your SwiftUI views.

    Live Object
    @Published
    Remarks
    Live Collection
    @Published
    Remarks

    hashtag
    Access AmityObject & AmityCollection in SwiftUI views

    Since AmityObject & AmityCollection are observable object, it can be used as an ObservedObject within SwiftUI views. We recommend to create small view which observes AmityCollection & AmityObject as ObservedObject as shown in code sample below.

    hashtag
    Live Object - SwiftUI

    Live Collection - SwiftUI

    Since the properties are published, If you are using Combine Framework, you can also subscribe to changes on those properties.

    Live Object - Combine

    Live Collection - Combine

    circle-info

    ℹ️ States of live collection & live object are published before snapshots so that you can compare the state from within subscriber.

    hashtag
    FAQ’s:

    #1: LiveCollection is not updated when used from inside of another observable class.

    AmityCollection & AmityObject is an ObservableObject. When this live collection or live object is embedded inside another Observable Object, SwiftUI cannot observe the changes in snapshot occurring within Live collection & Live object. As a result, there might be a situation where you see your view is not getting updated even when snapshot(s) are updated. This is a common problem with nested observable object in SwiftUI.

    To solve this issue we recommend to create a specific view which observes AmityCollection & AmityObject as @ObservedObject as shown in code example.

    #2: Published property still returns old values.

    Since the properties of AmityCollection & AmityObject are marked with @Published annotation, the publishing of changes occurs in the property’s willSet block, meaning that any subscribers will receive an update before the property is changed. This behaviour can easily lead to unexpected bugs.

    For more details, please refer to

    Poll Post

    Channels

    Our channels enable developers to implement different types of chat messaging capabilities into their applications easily

    In this section, we will cover the concept of channels in Amity Chat SDK and how to use them to enable different types of chat messaging capabilities in your application.

    circle-info

    Please be aware that there is some incompatibility between SDK version 5 and version 6 regarding the Subchannel feature.

    var client: AmityClient?
    client.clientErrorDelegate = self // set yourself as the delegate
    
    ...
    
    // Implement this delegate method which gets called when error occurs
    func didReceiveAsyncError(_ error: Error) {
            let error = error as NSError
            guard let amityError = AmityErrorCode(rawValue: error.code) else {
                assertionFailure("unknown error \(error.code), please report this code to Amity")
                return
            }
            
            if amityError == .globalBan {
                // Handle global ban event here
            }
        }
    client = new ASCClient({ apiKey, apiEndpoint });
    
    client.on('dataError', error => {
      if (error.code === ErrorCode.GlobalBanError) {
        // handle the case the user is globally banned
      }
    });
    image-text
    Followers/Following Collection
  • Channel Collection

  • Message Collection

  • Channel Member Collection

  • Community Collection

  • Community Members Collection

  • Any future changes to that data from any sources can trigger observer.
    : The actual object that is being tracked or encapsulated by this AmityObject

    3 (error) - Indicates that the data is unable to load due from a specific error.

    Any future changes to the data from any sources can trigger observer.

    snapshot

    ✅

    New

    error

    ✅

    -

    object

    ❌

    Deprecated

    snapshots

    ✅

    New

    error

    ✅

    New

    dataStatus

    ✅

    -

    loadingStatus

    ✅

    -

    dataStatus

    ✅

    -

    loadingStatus

    ✅

    -

    https://developer.apple.com/documentation/combine/publishedarrow-up-right
    Applications using SDK version 5 cannot view messages sent to subchannels by SDK version 6.
  • Channels can be sorted by 'Last Activity', which means that if messages are sent to SDK version 5 in subchannels, it moves the channel to the top of the collection. However, while the order will be updated to the top, the SDK version 5 will not display the message.

  • hashtag
    Channel and Subchannel Structure

    The concept of "channel and subchannel" is central to understanding how communication is structured in a chat SDK. Channels are the primary containers that hold subchannels, while subchannels are subdivisions within a channel that represent individual topics or chat threads.

    The relationship between a channel and its subchannels is hierarchical. A channel serves as a parent container for multiple subchannels, each of which represents a separate conversation or topic. Messages and interactions occur within subchannels, not the main channel itself. This organization allows for easier navigation and management of different conversations within a single channel.

    The differences between channels and subchannels are as follows:

    1. Function: Channels act as containers for subchannels, while subchannels are where actual conversations and interactions take place.

    2. Hierarchy: Channels serve as parent containers, whereas subchannels are subdivisions within a channel.

    3. Messages: Channels do not contain any messages directly; instead, all messages are stored within subchannels.

    4. Management: Users can create, update, delete, and query subchannels within a channel, managing each subchannel individually.

    5. Moderation: Moderation actions, such as banning, unbanning, muting, and unmuting users, can be performed at the channel level rather than the subchannel level. This approach ensures that moderation decisions apply to all subchannels within the main channel, providing consistent management across different conversations or topics.

    circle-info

    By default, when a channel is created, a corresponding default subchannel is also automatically generated.

    hashtag
    Channel Types

    Amity's Chat SDK has several channel types with different use cases. Each type is designed to match a particular use-case for chat channels.

    Channel Type

    Discoverable by

    Message sending privileges

    Moderation access

    Channel Creation

    Realtime Events Retrieval

    Community

    All users and admins

    Joined members and admins

    circle-info

    For further information about channel realtime events process, please visit Chat Realtime Events.

    hashtag
    Community and Private Community Channel

    The community channel is the default channel type and can be discovered by all users and admins. It acts as a public chat channel that showcases all of the features that our SDK's have to offer.

    hashtag
    Channel characteristics:

    • All users in the network can search for community channel

    • All users in the network can join the community without an invitation

    • Support @mention user

    • Support @mention all users in the channel

    • Appear on ASC Console for administrator to monitor

    hashtag
    Typical use cases:

    • Team collaboration

    • Online gaming

    • Celebrity fan club

    • Live streaming

    • Any type of public chat

    hashtag
    Live Channel

    Live channels offer the ability for users and admins to create channels with exclusive membership. The live channel is identical to our Community channel in features with the caveat that users will not be able to discover the channel when querying for all channels unless they are already a member of it. However, users and admins can still invite other users to join the channel.

    hashtag
    Channel characteristics

    • Can only be searched by member

    • Users can join if they know channel ID

    • Support @mention user

    • Support @mention channel users (mention all users)

    • Appear on the ASC console for administrator to monitor

    hashtag
    Typical use cases:

    • Chat channel for a one-time Live event

    hashtag
    Conversation

    Conversation channels is designed for 1-on-1 messaging and private small group chat. Unlike the other channel types, a Conversation channel can be created simply by knowing the userId of the user we want to converse with. Users can start conversations with any other user and only they will be able to see their conversation.

    Each channel has its own list of members, and no two channels can have the exact same member list. If someone tries to create a new channel with the same set of members as an existing channel, the system will return the existing channel. For example creating a new channel with User A and User B will always result in the same channel no matter how many time the create command is called. This is useful when trying to establish a private chat channel between 2 or more users as we want to make sure the user can continue using the existing channel that contains previous messages history.

    hashtag
    Channel characteristics

    • Channel is always unique with the same set of membership.

    • Support up to 10 members per conversation channel

    • Users can not join, leave, be added or removed from the channel once it's created

    • Users can not ban / unban other users in the channel

    • Does not appear on the ASC console for administrator to monitor

    • Does not support @mention user & @mention all

    hashtag
    Typical use cases:

    • 1:1 Chat Channel

    • Private Group Chat

    • Customer Support Chat

    Channel types can be created through SDK i.e Community, Live and Conversation. Creation of Private and Standard type has been removed. Creation of Broadcast channel type is not supported through the SDK. But for query, getChannels: method supports all channel types including Broadcast, Private and Standard.

    hashtag
    Broadcast

    The Broadcast channel is heavily adopted by corporate users who constantly promote or advertise their products, or make the announcement to drive awareness. Unlike other channel types, broadcast channels only allow admin users to send messages from Console, and everyone else in the channel will be under read-only mode.

    hashtag
    Broadcast channel characteristics

    • Broadcast message can only be sent out via ASC console

    • The administrator can choose to send to any community OR live channel (but not to the conversation channel).

    • Support @mention user

    • Support @mention channel users (mention all users)

    Typical use cases:

    • Marketing & Advertising

    • Organizational Announcements

    hashtag
    Channel Properties

    Name

    Data Type

    Description

    channelId

    String

    ID of the channel

    defaultSubchannelId

    String

    Channel Object is a Live Object and you can observe real-time changes in Channel Properties. Please see to Live Object on how to listen to real-time changes.

    Data type of the parameter is invalid.

    800210

    ConnectionError

    Websocket connection of the SDK cannot reach the platform server. This could also be the case if a user is global-banned and try to register a session.

    Create Channel

    ChannelRepository offers a function to create a new channel. This function provides support for creating three distinct types of channels, including Community, Live, and Conversation. Each channel type has its own unique characteristics and capabilities as we explained earlier, and the create channel function allows users to easily create and customize channels to suit their specific needs.

    The SDK offers two standard ways for creating channels. The first method involves specifying a specific channel ID during the channel creation process. The second method allows for the automatic generation of a unique channel ID. The create channel API is designed to ensure that the channel being created is a new channel, and in the event that the requested channel already exists, it will return a conflict error (400900). The channel ID parameter in the channel creation function may be left undefined, in which case the SDK will automatically generate a unique channel ID to avoid any conflicts with existing IDs.

    hashtag
    Create Community Channel

    This function on the SDK allows you to create a new . The displayName parameter is a required field, and it represents the public display name of the channel.

    Here is a brief explanation of the function parameters:

    • displayName: The public display name of the channel.

    • avatarFileId: The image fileId that represents the image of the channel.

    • metaData

    Supported ✅ (please wait while we prepare a real example!)

    Version 6

    Beta (v0.0.1)

    hashtag
    Create Live Channel

    Similar to community channel creation function, the function allows you to create a new . The displayName parameter is a required field, and it represents the public display name of the channel.

    Here is a brief explanation of the function parameters:

    • displayName: The public display name of the channel.

    • avatarFileId: The image fileId that represents the image of the channel.

    • metaData

    Version 6

    Beta (v0.0.1)

    hashtag
    Create Conversation Channel

    The channel creation function can also be utilized to create channels of the Conversation type. However, it should be noted that the channel ID for these channels will always be generated by the SDK. This ensures that the channel ID is unique and avoids any potential conflicts with existing channels

    Here is a brief explanation of the function parameters:

    • userId: The userId of the user that you'd like to chat with.

    • displayName: The public display name of the channel.

    • avatarFileId

    circle-info

    Conversation channel is unique based on its membership. When creating conversation, the system will check if a channel with the same membership already exists. If such channel already exists, the system will return the existing channel instead of creating a new one.

    Version 6

    Beta (v0.0.1)

    hashtag
    Create Broadcast Channel

    channel can only be created from Amity Social Cloud Console. We recommend to see instructions in on how to create a Broadcast channel.

    Reaction Reference Type
    import { ErrorCode, CommunityRepository } from '@amityco/js-sdk'
    
    const liveObject = CommunityRepository.communityForId('abc');
    liveObject.on("dataUpdated", data => {
      // community is fetched
    });
    liveObject.on("dataError", err => {
      // failed to fetch the community 
      console.log(err.code == ErrorCode.BusinessError);
    }

    All Moderation tools

    SDK, Console

    Automatic

    Private Community

    Joined members and admins

    Joined members and admins

    All Moderation tools

    SDK, Console

    Automatic

    Live

    Joined members and admins

    Joined members and admins

    All Moderation tools

    SDK, Console

    Subscription needed

    Broadcast

    All users and admins

    Admins

    Admin Moderation tools

    Console

    Subscription needed

    Conversation

    Joined members

    Joined members

    No Moderation tools

    SDK

    Automatic

    ID of the default subchannel that's generated upon channel creation

    isDistinct

    Bool

    Is channel distinct?

    metadata

    JsonObject

    Additional properties to support custom fields

    type

    AmityChannelType

    Type of channel

    tags

    Array<String>

    Tags used for searching

    isMuted

    Bool

    Is this channel muted?

    isRateLimited

    Bool

    This channel has limited sending rate?

    rateLimit

    Int

    Number of messages within rate limit

    displayName

    String

    Channel name for displaying

    memberCount

    Integer

    Number of members in channel

    messageCount

    Integer

    Number of messages in channel

    unreadCount

    Integer

    Number of unread messages in channel

    lastActivity

    DateTime

    Date/time of user's last activity related to the channel (e.g. add/remove member)

    createdAt

    DateTime

    Date/time the channel was created

    updatedAt

    DateTime

    Date/time the channel was last updated

    avatarFileId

    String

    Avatar file ID

    isPublic

    Bool

    Public / Private community channel

    : Additional properties to support custom fields.
  • tags - Arbitrary strings that can be used for defining and querying for the channels.

  • isPublic - Specify visibility for the community channel that public or private community.

  • : Additional properties to support custom fields.
  • tags - Arbitrary strings that can be used for defining and querying for the channels.

  • : The image fileId that represents the image of the channel.
  • metaData: Additional properties to support custom fields.

  • tags - Arbitrary strings that can be used for defining and querying for the channels.

  • Channels
    Live Channel
    Conversation
    Broadcast
    Poll Post
    import { ChannelRepository, ChannelType } from '@amityco/js-sdk';
    
    const liveChannel = ChannelRepository.createChannel({
      channelId: 'channel1',
      type: ChannelType.Community,
      userIds: [ 'user1', 'user2' ],
    })
    
    liveChannel.once('dataUpdated', model => {
      console.log(`Channel created: ${model.channelId}`);
    });
    
    liveChannel.once('dataError', error => {
      // Handle channel create error (non-unique channelID)
    });
    import { ChannelRepository, ChannelType } from "@amityco/js-sdk"
    
    const liveChannel = ChannelRepository.createChannel({ type: ChannelType.Conversation })
    
    liveChannel.once('dataUpdated', () => {
      console.log('channel created');
    });
    

    Get and View a Message

    To view the content of a message using the Amity Chat SDK, developers can utilize a message object. The message content can then be used to display to the user in a chat interface, or to perform other operations on the message data as needed. This allows developers to build chat applications that support messaging using the Amity Chat SDK and provides a foundation for building more advanced chat applications that require more complex message handling and processing. The Amity Chat SDK provides several methods for viewing messages in a chat channel. Here's how to use these methods in your app:

    hashtag
    Get a single message

    To get a single message by its ID, use the getting message function of the Amity Chat SDK. This method returns a message live object, which you can use to display the message in your app. Here's an example:

    You can use the getMessage method to get a single comment. You need to pass the messageId of the requested message as the parameter.

    The method returns a liveobject instance of a message model. It will throw an error if the passed messageId is not valid.

    Version 6 and Beta

    Supported ✅ (please wait while we prepare a real example!)

    hashtag
    Get messages with a query

    You can also use a query to get messages that match specific criteria. The querying and filtering messages function of the Amity Chat SDK enables you to retrieve messages based on different parameters such as a specific user, a date range, or a keyword search. please refer to the page -

    hashtag
    View a message

    hashtag
    Text Message

    This is the most basic type of message, and is useful for sending simple messages such as chat messages, system notifications, or status updates. Each text message has a character limit of 20,000 characters, making it suitable for sending concise messages.

    v6.0.0 and Beta

    hashtag
    Image Message

    Sending visual content such as photos, graphics, or images in a channel is facilitated by this type of message. The maximum size for an image is 1 GB, and the image will be automatically transformed into four different sizes for versatile usage which are:

    • Small

    • Medium

    • Large

    This allows for flexible usage and easy integration into various chat applications. For more information about an image, please refer to the page - .

    Version 6

    In TypeScript SDK, viewing a file, image, and audio message have the same steps and sample code. You can query all file types with observeFile.

    Beta (v0.0.1)

    hashtag
    File Message

    This is a message that contains a file attachment, such as a PDF, a Word document, or any other type of file. This is a useful type of message for sharing files within a channel, such as a document or a photo. The maximum size for a file is 1 GB. For more information about a file, please refer to the page -

    circle-info

    In iOS SDK, AmityFileRepository provides downloadFile: and downloadFileAsData: method to download the file from URL. The same method can be used to download the audio.

    hashtag
    Video Message

    This is a useful type of message for sharing video content within a chat conversation, such as a short clip or a longer video. The maximum size for a video is 1 GB, and the video will be automatically transcoded into different resolutions for versatile usage which are

    • 1080p

    • 720p

    • 480p

    Once you uploaded a video the videos undergo transcoding from their original resolution. You can quickly access the original size of the video right after you make the video message. However, it takes time for the transcoded resolutions to be ready. This allows for flexible usage and easy integration into various chat application. For more information about a video, please refer to the page - .

    Supported ✅ (please wait while we prepare a real example!)

    hashtag
    Custom Message

    In addition to the built-in message types such as text, image, file, audio, and video, the Amity Chat SDK also provides support for "custom messages". Custom messages allow users to design their own JSON structure that can be used to represent any kind of data, essentially providing the freedom to create their own message types.

    This can be useful for a variety of use cases. For example, a developer building a chat application for a sports team could use custom messages to create a "score update" message type that contains data such as the score of a game, the time remaining, and other relevant information. Similarly, a developer building a chat application for an e-commerce platform could use custom messages to create a "product update" message type that contains information such as product details, availability, pricing, and other relevant data.

    The possibilities for custom messages are endless, and can be tailored to the specific needs of any application. Custom messages can be sent and received using the Amity Chat SDK, and can be queried and displayed in a chat channel just like any other message type.

    Supported ✅ (please wait while we prepare a real example!)

    For custom messages, the data is in the data property.

    Observing the LiveObject for ban while having a session
    AmityError enums map to the supported error scenarios
    Banned while not having a session
    Get a fresh object
    Live Object observation is bound to a token
    Call nextPage() / previousPage() to load more data
    Observe a Live Collection
    Iterate each object in a live collection using .allObjects()
    An equivalent implementation of .allObjects()
    AmityNotification is alive in MyClass scope.
    Full
    360p
  • original

  • Query and Filter Messages
    Image Handling
    File Handling
    Video Handling

    Installation and Authentication

    This section outlines how you can set-up your ASC project and contains all the tutorial links you'll need to get going .

    SDK Installation

    For instructions on installing the Amity Social Cloud SDK, refer to the installation guide for your platform.

    • iOS

    We are constantly working to improve our existing SDKs. For this reason, the minimum compatibility for our previous versions may vary. Below is the compatibility list for our latest SDKversions. For a complete overview of the compatibility of a specific SDK version, please refer to the corresponding .

    • Xcode Version: 14.3

    • Realm Version: 10.28.3

    • Minimum Target: iOS 13.0

    hashtag
    Initialization

    Before you can use the ASC SDK you just installed, we'll first need to create a new SDK instance with your API key. Please find your account API key in the or visit our page.

    After logging into Console:

    1. Click Settings to expand the menu.

    2. Select Security.

    3. In the Security page, you can find the API key in the Keys section.

    If you have trouble finding this, you can post in our community forum at so our support team can assist you.

    hashtag
    Specify Endpoints Manually (Optional)

    By default, AmityClient will connect to AmityRegion.SG.You can specify endpoints manually via AmityEndpoint struct. API endpoints for each data center are different so you need to adjust the endpoint accordingly.

    circle-info

    Note: From Js SDK v5.10.0, we introduced Real time events which requires a new endpoint (mqttEndpoint) along with the existing apiEndpoint. So instead of passing multiple parameters for both, we can pass a single apiRegion parameter. The corresponding endpoints will then be created within the SDK using the passed region. This will be the recommended approach to create a new ASClient for different regions.

    We currently support multi-data center capabilities for the following regions:

    hashtag
    Specify database encryption mode (Optional)

    The SDK does not employ database encryption by default. The database file is solely restricted to the application by the operating system, which is generally sufficient for most use cases. Database encryption serves as an additional layer of security in the event of compromised root access. It's important to note that enabling database encryption may lead to a performance reduction of up to 15% during database read/write operations.

    circle-info

    Please note that we only support database encryption for Android SDK 5.35.0 and v6, beginning from version 6.16.0 onwards.

    Database Encryption Modes:

    The SDK offers three encryption modes:

    1. NONE: No encryption is applied.

    2. AUTH: Access token storage is encrypted.

    3. ALL: All database files are encrypted.

    AUTH mode is recommended to introduce extra security with minimal performance compromise. Ultimately, the chosen encryption mode should align with your application's specific requirements.

    Encryption key:

    Enabling database encryption necessitates an encryption key. It is imperative to consistently pass the same key to the SDK. Should a new key be supplied, the existing database file will be erased and subsequently regenerated, encrypted with the new key.

    The level of security offered by encryption hinges on the method of key generation and storage employed by the application. It is strongly recommended to adhere to industry standards for both key storage and generation.

    hashtag
    Authentication

    In order to use any ASC SDK feature, you must first log in the current device with a userId. A logged in device will be tied to the userId until the device is either proactively logged out, or until the device has been inactive for over 90 days. A logged in device will receive all the events messages belonging to the tied user.

    An optional displayName can be provided, which will be used in standard push notifications (related to user's actions, such as when the new message is sent).

    An authToken is also highly recommended to always be provided, which will be used for a secure authentication. For more info on how to configure secure settings and obtain authToken, refer to our .

    A sessionHandler is required for SDK to communicate with the app. For more info please refer to . Do note that the sessionHandler is not yet available for Flutter SDK.

    circle-exclamation

    It is important to maintain the security of your network and user information. In production environment, we strongly recommend using an authToken for authentication. While the option to not use an authToken may be available, it should only be applied during the development phase and with caution.

    The displayName is set only on the first time the device is logged in. Please follow your platform's necessary directions if you would like to rename this to something else.

    hashtag
    Logout

    When the user logs out, you should explicitly log out the user from the SDK as well. This prevents the current device from receiving unnecessary and/or restricted data.

    circle-info

    Logout is a synchronous operation. Once the logout method is called, the SDK disconnects from the server and wipes out user session.

    circle-info

    hashtag
    Disconnect

    After the SDK is logged in with a user, SDK will maintain the connection as long as it can. However the SDK connection can be terminated due to many reasons, for example:

    • The device lost Internet connection.

    • Users close the app into the background, then the operating system pauses the app, and terminates all network connections.

    By default the SDK automatically reconnects itself whenever the app has a chance to get back online.

    There are some use-cases that developers need more control over the SDK connection. The SDK provides disconnect(). This method allows developers to explicitly disconnect the SDK while maintaining the current user session so that the app can later resume the connection with the same user.

    The functionality isn't currently supported by this SDK.

    When developers call disconnect():

    • The SDK will terminate server connections without logging out the current user.

    • The SDK will not automatically reconnect until the next login.

    To resume the connection, the developers should call login(...) with the current user.

    hashtag
    Devices

    Each user can be logged in, at the same time, to an unlimited number of devices. Amity's Chat SDK will automatically synchronize the user data across all logged in devices. We will also automatically log out any device that has not been connected to the server for more than 90 days.

    When a device is logged out due to inactivity, the SDK data on the device will be reset. You will need to re-login this device in order to connect to server again.

    hashtag
    Tutorials

    Now that you've finished getting your ASC project set up, here are some step-by-step articles if you need a hand building your app!

    chevron-rightVisualized Code Exampleshashtag

    Yes, you're reading it right! Here you can visually learn how your changes could affect the code, compare your work, and see our development pattern recommendations.

    Are you ready? Click to explore.

    chevron-rightAll Your UIKit Needshashtag

    How to Create a Social App with ASC

    Explore a step-by-step tutorial by our engineers to help you build your own Social application. Let's get started in creating an amazing user experience platform.

    chevron-rightCreating Notifications and Webhooks with NodeJshashtag

    Push notifications are proven to be one of the best ways to drive & increase user engagement with the platform and with Amity Social Cloud. ...

    chevron-rightBuilding an Android Image Feed Applicationhashtag

    Engage your users through image activity feeds as known from known social networks like Instagram and Pinterest.

    hashtag
    Amity Social Cloud Developer Kits

    Check out our Amity Social Cloud UI Kits and Template Apps.

    • UI Kits Our UI Kits include user interfaces to enable fast integration of standard Amity Chat and Amity Social features into new or existing applications.

    • Template Apps Our Template Apps are ready-made template applications to kickstart your own Amity Social Cloud project.

    With real-life use-cases, we guide you through ways you can get started with building stellar applications for yourself and your clients and their users.

    Technical FAQ

    Explore our Technical FAQ for quick answers to common questions about Amity products. Get troubleshooting tips, best practices, and insights to optimize your technical experience.

    hashtag
    API

    chevron-rightHow do I create a large number of users in bulk on Amity?hashtag

    To create a large number of users, it's advised to use the following endpoint: .

    chevron-rightWhat should I use as the 'Authorization' token when I need to perform admin actions?hashtag

    To obtain your admin token, please follow these steps on the :

    1. Navigate to "Settings" > "Admin Users"

    chevron-rightHow can I retrieve the next page of data from an API?hashtag

    To retrieve the next page of data from an API, you should use the "next" page token provided at the end of the initial page's results. This token should be appended to the endpoint to fetch the values for the next page.

    Here's an example:

    To get the next page of data, append the "next" token to the endpoint like this:

    Next Page API Request:

    chevron-rightHow can I upload a bulk list of blocklisted words?hashtag

    You can upload a bulk list of blocklisted words using an example like this:

    In this example, replace "word1," "word2," and "word3" with the blocklisted words you want to upload in bulk. The request includes the necessary headers and data to add the specified words to the blocklist.

    Setting isMatchExactWord to true makes the blocklisting more strict and will only block exact matches, while setting it to false

    chevron-rightHow can I modify my follow/unfollow settings?hashtag

    You can adjust your follow/unfollow settings by making an API call to the following endpoint: . Please refer to the example below to understand the structure:

    chevron-rightHow can I obtain higher-quality images?hashtag

    For higher-quality images, you can enhance the resolution by simply adding ?size=full to the end of the URL.

    Example: .

    Additionally, you have the flexibility to specify the size as "small," "medium," "large," or "full" based on your preferences.

    chevron-rightWhat is a refreshToken?hashtag

    A refreshToken is primarily employed by SDKs to validate the accessToken's validity. When using the API, obtaining a new token can be achieved by making a "register session" API call, eliminating the need to directly manage or use a refreshToken.

    chevron-rightHow long does the authentication token last?hashtag

    The authentication token has a duration of 10 minutes, and it must be used within that specific time frame. For further information on secure mode and authentication tokens, please refer to this section:


    hashtag
    Social and Chat

    chevron-rightWhat is the purpose of targetType and targetId?hashtag

    The targetType and targetId parameters are essential in query options for fetching posts from a specific feed.

    • targetType specifies the type of feed, which can be either ‘user’ or ‘community’.

    chevron-rightIs it possible to sort posts within a community by engagement, similar to the global feed?hashtag

    Currently, posts within a community can’t be sorted by engagement like the global feed. The available sorting options for community posts are ‘lastCreated’ and ‘firstCreated’.

    For more information on how to implement these sorting options, you can refer to the Amity SDK documentation on querying posts: https://docs.amity.co/amity-sdk/social/posts/query-post

    chevron-rightHow can I query communities while excluding the ones that have been deleted?hashtag

    To exclude deleted communities from your query results, you can use different methods depending on whether you’re using the API or SDK:

    1. Using the API: When querying communities through the API at: , include the parameter isDeleted: false in your request. This will filter out any deleted communities from the results.

    chevron-rightIs there a way to check which communities a user is part of?hashtag

    Due to privacy and design considerations, it’s not possible to query communities joined by other users, even if you are an admin. However, the current user can query the communities they have joined themselves. This can be done through the API, as detailed at: , by filtering for membership.

    Alternatively, you can use the SDK, as explained in Amity SDK - Query Communities https://docs.amity.co/amity-sdk/social/communities/query-communities.

    chevron-rightWhy does querying a list of objects only return 20 items in the response?hashtag

    This behaviour is due to pagination implemented in our API endpoints and functions, which default to returning 20 items per page. To access more items, you need to use the next page token (Please refer to the API section above) or the nextPage() function, depending on the SDK you’re utilizing.

    For detailed information on how pagination works for different SDKs, please refer to the Live Objects/Collections section in our documentation here: https://docs.amity.co/amity-sdk/core-concepts/live-objects-collections

    chevron-rightHow can I update a community user’s role?hashtag

    To update a user’s role in a community, you have two options:

    1. Using API: with the following cURL command:

    chevron-rightHow can I remove members from a community?hashtag

    Members can be removed either through the SDK, as detailed here: https://docs.amity.co/amity-sdk/social/communities/community-moderation#remove-members, or by using the API, found at: .

    chevron-rightHow can I delete a community?hashtag

    You can delete a community using the API provided here: Alternatively, for admin users, you can also close a community directly from the .

    Here's how:

    • Navigate to the Community tab in the console.

    chevron-rightDoes the JavaScript SDK support Unread Count?hashtag

    Yes, the JavaScript SDK includes support for a legacy unread count. You can find more information here: https://docs.amity.co/amity-sdk/chat/channels/read-status-and-unread-count-legacy.

    Note: The unread count in the JavaScript SDK only supports the channel unread count from the default subchannel. Since the JS SDK does not support subchannels, all unread counts from subchannels will not be included.

    Please refer to this section for more information related to channels and subchannels: https://docs.amity.co/amity-sdk/chat/channels#channel-and-subchannel-structure

    chevron-rightI don't want the global feed to be empty for new users. How can I add some posts there?hashtag

    You can implement an auto-join function, which can be called after a new user is created. To achieve this, use the join community API, which you can find here: . By doing this, existing posts in those particular communities will be displayed as the initial content in the global feed for new users.

    chevron-rightWhat is metadata and its intended use?hashtag

    Metadata consists of additional properties designed for custom fields. It serves to store supplementary data related to specific objects, like a user object, but isn't suitable for large amounts of data or information.

    Please note that metadata has a size limit and it is recommended to keep it below 1000 bytes.

    chevron-rightWhy is my global feed empty?hashtag

    The global feed aggregates posts from communities you have joined and from users you are following. If you haven’t joined any communities or followed any users, there will be no posts for the global feed to display.

    chevron-rightWhat are the image requirements for uploading?hashtag

    The supported image formats for upload are JPG and PNG. Each image must not exceed 1GB in size. A post can contain up to ten images. Additionally, on the iOS platform, any uploaded images or videos in unsupported formats, like HEIC or HEVC, will be automatically converted to PNG.

    chevron-rightWhat are the videos requirements for uploading?hashtag

    The supported video formats include 3gp, avi, f4v, flv, m4v, mov, mp4, ogv, 3g2, wmv, vob, webm, and mkv. Videos must not exceed 1 GB in size and should have a maximum duration of 2 hours. Each post can contain up to ten videos.

    Please note that uploading HDR video format is not supported on iOS.

    chevron-rightAfter enabling secure mode and obtaining the auth token, do I need to generate an access token? What should I do with the auth token if I’m using the SDK?hashtag

    When using the SDK, you only need the auth token, which should be provided when a user logs in or creates an account. The SDK will manage the process thereafter. For more information, you can refer to the Amity SDK documentation on user creation: https://docs.amity.co/amity-sdk/core-concepts/user/create-user

    chevron-rightWhy are the posts on my global feed not sorted by the most recently created?hashtag

    Our global feed offers multiple sorting options, including sorting by factors such as Engagement Rate, Time of Posting, and Updates. It's possible that your feed is currently sorted by other factors, if you wish to update or adjust the feed configuration, please reach out to our support team at

    For more detailed information on custom post ranking, you can also refer to our documentation at:


    hashtag
    iOS

    chevron-rightWhat should I do if push notifications on iOS are not working?hashtag

    If you already followed our docs here:

    chevron-rightCan I use my own realm in an iOS project?hashtag

    No, we would recommend you use our realm which is included in the iOS SDK and UIkit. You can check the compatible version between the iOS SDK and Realm on our changelog page in compatibility section and adjust the version accordingly.

    For more information on the iOS SDK and UIKit, you can visit:

    chevron-rightWhat type of certificate do I need to register push notification on iOS?hashtag

    To register push notifications on iOS, you'll require a .p12 certificate. During the process, make sure to select "Apple Push Notification Service SSL (Sandbox & Production)"

    For detailed instructions on setting up an iOS push certificate, please consult this documentation: .


    hashtag
    Poll

    chevron-rightWhat is the method for obtaining the list of voters for a specific answer in a poll?hashtag

    To get the voters for a specific answer in a poll, you can utilize the API endpoint provided: . This API will return the user IDs of the voters along with their answers in the response.

    hashtag
    Console

    chevron-rightWhere can I get my admin token?hashtag

    To obtain your admin token, please follow these steps on the :

    1. Navigate to "Settings" > "Admin Users"

    chevron-rightHow do I grant console access to my team members?hashtag

    First, your portal owner/head of admins needs to create the initial admin user on the console. Subsequent admin users can then create or grant access to additional team members. To do this, navigate to ‘Settings’ > ‘Admin Users’ and click on the ‘Create New Admin’ button located at the top right of the page. Fill in the username and password; team members can use these credentials to access the console.

    chevron-rightWho can upload a PNS Certificate file to the Push Notification section and how is it done?hashtag

    Initially, only the portal owner has the capability to upload the PNS Certificate. They will find the option to do so by clicking on the “+ Add new certificate” button, which is exclusively available to them for the first upload.

    chevron-rightWhy can't I retrieve posts from communities that a user has posted in when I use the 'User' option in the Post Management on Amity console?hashtag

    The 'User' option, found under the 'Posts' section with 'User' selected in the dropdown menu, is specifically meant for fetching posts from a user's feed. Please note that it is not intended to retrieve posts from communities where a user has posted, based solely on the user's ID.

    chevron-rightHow can I obtain my API key and application region (endpoint)?hashtag

    Please log in to your console, and you will find your API key and app region (endpoint) in the "Settings" > "Security" tab.


    hashtag
    Portal

    chevron-rightHow do I create new app environments for different purposes, such as testing and production?hashtag

    To create new app environments for various purposes, like testing or production, follow these steps:

    1. Log in to your .

    chevron-rightHow do I upgrade my application pricing plan?hashtag

    To upgrade your application's pricing plan, follow these steps:

    1. Create a new application in the portal and select the desired plan, such as "ASC Advance."

    Next, provide us with the following information:

    chevron-rightHow can I access the portal, it says my email is invalid?hashtag


    hashtag
    Alternative solutions for unsupported features

    chevron-rightHow can I implement a feature that allows users to save their favourite posts?hashtag

    For this use case, you can use our user's object metadata field to store the postId of the posts the user wants to save so that they can be extracted and fetched later. The saved content can be accessed from the user's profile or a dedicated section within the user interface. The exact implementation and design of this feature can vary depending on the specific requirements and design of your application.

    chevron-rightHow can I add a Verified badge (blue tick) for users?hashtag

    To add a Verified badge to a user’s profile, you need to update their user object’s metadata by including a ‘verified’ label. Once this label is in place, the frontend system can retrieve this information and display the Verified badge, styled as a blue tick or as per your custom design preferences. The verification process, governed by your frontend logic, ensures that the account meets your criteria for verification. After the account is verified according to these standards, you can then insert the ‘verified’ label into the metadata of the user’s profile.

    chevron-rightIs there an option for users to accept or decline invitations to join a community?hashtag

    While our product does not directly provide this feature, you can implement it on your end by updating the metadata of users. Invited users’ metadata can include an ‘invitedCommunity’ list. You can extract this list to query community details and display them. Once a user accepts or declines the invitation, the CommunityID will be removed from their metadata.

    chevron-rightHow can I retrieve community posts by a specific user ID?hashtag

    Unfortunately, you cannot achieve this directly via the SDK or API, as community feed and user feed are separate. You can choose to fetch posts from either the community feed or the user feed individually. However, you can meet this requirement by using content search. For more details, please refer to the section.

    If you're interested in trying this feature, please note that you'll need to enable it first. To do so, please get in touch with our support team at . They will assist you further with enabling content search for your application.

    chevron-rightHow to implement post sharing feature?hashtag
    1. To share a post, create a new post and specify the destination target for the shared content.

    2. In the metadata of the newly created post, include the original post's ID, for instance: "originalPostID": "abc"

    chevron-rightHow can I set up email notifications for specific actions in my community, such as when a post is flagged?hashtag

    For email notifications, you can leverage our webhook events triggered when a post is flagged. You can find more details in the documentation here:


    hashtag
    Beta features

    chevron-rightHow can I filter out deleted communities in content search?hashtag

    To exclude deleted communities from your content search results, you need to include isDeleted: false within the query section of your request body.

    Here’s an example to illustrate the placement:

    chevron-rightHow do you implement push notifications in Web React and React Native?hashtag

    To implement push notifications in Web React JS and React Native, you can utilize our . These events provide real-time updates on new posts and comments, including sender and receiver information. You can use this data to customize your push notifications with specific labels, details, and payload.

    For a complete list of available webhook events, please visit: https://api-docs.amity.co/#/WebhookEvent

    chevron-rightHow does pagination work in content search?hashtag

    Pagination in content search is managed through two parameters:

    1. from: This parameter sets the offset from the first result to be fetched.

    chevron-rightHow can I exclude deleted posts or messages from being returned in content search?hashtag

    You can achieve this by adding the following condition to your query:

    By setting "isDeleted": false, you ensure that only posts or messages marked as not deleted will be included in the search results.

    chevron-rightWhy does content search return fewer posts than the user has?hashtag

    Content search will only return posts that were created after the content search feature was enabled. Posts created before the enablement will not be included in the content search response.

    Please be aware that only posts created after the feature was enabled will be part of the search results.


    hashtag
    Frequent error types: Definition

    chevron-rightWhy am I encountering this error “Error: Connect client first”?hashtag

    This error typically arises when an SDK function is called before successfully establishing a connection to the Amity session. To resolve this, ensure that you call UserRepository related functions only after the session state is set to ‘established’. You can monitor the session state using the following code snippet:

    This code tracks the session state, and you should proceed with calling SDK functions once the state confirms the session is established.

    chevron-rightI received the error “Query Token is invalid” What should I pass as the query token in Swagger?hashtag

    The error indicates a problem with the pagination token. In the result response, a pagination token is provided at the end of the first page. You should use this token to fetch subsequent pages. The response typically includes a "paging" section with "next" and "previous" strings, like this:

    Use the value from the ‘next’ or ‘previous’ string as your query token to access additional pages.

    chevron-rightWhat does the error "Unable to use SDK while the SDK is logging in" mean?hashtag

    This error occurs when the SDK login process is in progress while other actions are attempted. To resolve this, you should ensure that other actions are initiated only after the login process has successfully completed.

    chevron-rightWhat does the error "RateLimit Exceed" mean?hashtag

    Our API/function is subject to a limit of 10 calls per second per user. To avoid encountering this error, it is important to carefully monitor and control the number of calls made to ensure they do not exceed this defined limit.

    chevron-rightWhat should I do when I encounter error code 400314 while attempting to post content with an image?hashtag

    If you've encountered error code 400314 while trying to post content containing an image, it is likely related to our image moderation settings. To address this issue, follow these steps:

    1. Confirm whether you have enabled image moderation in your console settings. You can do this by accessing the and checking the image moderation settings under Settings > Image Moderation tab.

    chevron-rightWhy am I unable to post a link and receiving error 400309?hashtag

    This error occurs because we have link moderation in place. You can manage this feature in the by going to "Moderation" > "Allow list" tab. If the feature is enabled, links that have not been added to the allow list will not be permitted to be posted in the community or chat.


    hashtag
    General

    chevron-rightCan a user be restored after deletion?hashtag

    Once a user is deleted using the API : , it is not possible to undo this action. The user is permanently removed.

    chevron-rightHow can I delete inactive users?hashtag

    To delete inactive users, you can make use of the following API call:

    Here's an example:

    After the user is deleted, their display name will be automatically changed to 'Deleted user'. Please be aware that once users are deleted, there is no way to restore them.

    chevron-rightWhat are the consequences for a user who is globally banned?hashtag

    When a user is globally banned by an admin, they lose the ability to authenticate with ASC and are automatically removed from all their existing channels. Additionally, all of the banned user’s messages are deleted, although if these messages are already cached in the SDK, they will only disappear upon refreshing.

    However, the user’s social content, including posts, comments, and community memberships, remains intact.

    The globally banned user will be unable to authenticate with Amity’s network again until the global ban is lifted.

    chevron-rightHow are concurrent connections counted when a user opens multiple tabs?hashtag

    Concurrent connections are counted on a per-device basis, rather than by the number of browsers or tabs. For instance, if a user connects from two different devices, it counts as two concurrent connections.

    chevron-rightIs there a dark theme option available in Amity?hashtag

    Amity does not fully support a dark theme at the moment. However, you can customize the UI to create a dark theme using our open-source UIKit, which offers flexible UI customization options.

    chevron-rightHow do I delete an unused application?hashtag

    To delete an unused application, please contact our support team at , and they will assist you in fulfilling your request.

    chevron-rightWhat defines an inactive user?hashtag

    Inactive users are defined as the total unique users, identified by their user IDs, who have registered within the Amity Social Cloud system but have not established any connection to any Amity Social Cloud network during the specific month for which the Monthly Active User (MAU) count is being calculated. This includes users who may have registered at any time in the past, such as someone who signed up in January but has been inactive since then, and are still considered inactive in the subsequent months like May.

    chevron-rightWhere can I download Figma files?hashtag

    You can download Figma files from the following links:

    • For Social Figma file: .

    For further assistance or if you have any questions, or require clarification on any technical matters, please do not hesitate to reach out to our dedicated support team at [email protected]

    Invalidate a token
    Using a live collection with UITableView
    Get a local data
    Observe a Fresh Live Collection
    import { MessageRepository } from '@amityco/js-sdk';
    
    const liveObject = MessageRepository.getMessage('messageId');
    let message = liveObject.model;
    
    liveObject .on('dataUpdated', data => {
      message = data;
    });
    
    liveObject .on('dataError', error => {
      console.error(error);
    });
    
    // unobserve data changes once you are finished
    liveObject.dispose();
    import React, { useEffect, useState } from 'react';
    import { FileRepository, MessageType } from '@amityco/js-sdk';
    
    // renders a text message
    const TextContent = ({ data, fileId }) => {
      return data?.text ? <p>{data!.text}</p> : null;
    }
    import React, { useEffect, useState } from 'react';
    import { FileRepository } from '@amityco/js-sdk';
    
    const ImageMessageContent = ({ data, fileId }) => {
      const [file, setFile] = useState();
    
      useEffect(() => {
        const liveObject = FileRepository.getFile(fileId);
    
        liveObject.on('dataUpdated', setFile);
        liveObject.model && setFile(liveObject.model);
    
        return () => liveObject.dispose()
      }, [fileId])
    
      return (
        <>
          {data?.caption && <p>{data!.caption}</p>}
          {file && <img src={file.fileUrl} />}
        </>
      )
    }
    import React, { useEffect, useState } from 'react';
    import { FileRepository, MessageType } from '@amityco/js-sdk';
    
    // renders a file message
    const FileContent = ({ data, fileId }) => {
      const [file, setFile] = useState();
    
      useEffect(() => {
        const liveObject = FileRepository.getFile(fileId);
    
        liveObject.on('dataUpdated', setFile);
        liveObject.model && setFile(liveObject.model);
    
        return () => liveObject.dispose()
      }, [fileId])
    
      return (
        <>
          {file && <a href={file.fileUrl} download>{file.attributes.name}</a>}
          {data?.caption && <p>{data!.caption}</p>}
        </>
      )
    }
  • OKHTTP3 - 4.9.0

  • Retrofit - 2.50

  • Android Paging Data Library - 3.0.1

  • Room - 2.4.0-alpha04

  • RxJava2 - 2.3.10

  • Gson - 2.8.10

  • Kotlin-std-lib - 1.5.10

  • HiveMQ mqtt client - 1.2.2

  • hashtag
    Transitive Library Dependencies

    • androidx.annotation:annotation: 1.2.0

    • androidx.core:core-ktx: 1.3.2

    • androidx.paging:paging-runtime: 3.0.1

    • androidx.paging:paging-rxjava2: 3.0.1

    • androidx.lifecycle:lifecycle-livedata: 2.2.0

    • androidx.lifecycle:lifecycle-reactivestreams:2.1.0-rc01

    • androidx.multidex:multidex:2.0.1

    • androidx.room:room-runtime:2.3.0

    • androidx.room:room-rxjava2:2.3.0

    • com.f2prateek.rx.preferences2:rx-preferences:2.0.1

    • com.github.davidmoten:rxjava2-extras:0.1.24

    • com.google.code.gson:gson: 2.8.7

    • com.google.guava:guava:30.1.1-android

    • com.jakewharton.rxrelay2:rxrelay:2.0.0

    • com.jakewharton.rx2:replaying-share:2.0.1

    • com.jakewharton.timber:timber:4.7.1

    • com.squareup.okhttp3:okhttp: 4.9.0

    • com.squareup.okhttp3:logging-interceptor:3.10.0

    • com.squareup.retrofit2:retrofit: 2.5.0

    • com.squareup.retrofit2:adapter-rxjava2: 2.5.0

    • com.squareup.retrofit2:converter-gson: 2.5.0

    • io.arrow-kt:arrow-core:0.11.0

    • io.arrow-kt:arrow-syntax:0.11.0

    • io.reactivex.rxjava2:rxandroid: 2.1.1

    • io.reactivex.rxjava2:rxjava: 2.2.19

    • io.socket:socket.io-client:1.0.0

    • joda-time:joda-time:2.10.6

    • org.apache.commons:commons-lang3:3.7

    • org.jetbrains.kotlin:kotlin-stdlib: 1.5.10

    • org.jetbrains.kotlin:kotlin-android-extensions-runtime: 1.5.10

    • org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.3

    • Chrome: 38+

    • Firefox: 42+

    • Microsoft Edge: 13+

    • Safari: 9+

    • Opera: 25+

    triangle-exclamation

    Amity JS SDK probably won't work great in Internet Explorer 11. We generally support the recent versions of major browsers listed above.

    Since Amity Js SDK uses local cache for performance and user experience reason, server side rendering is not supported. To use Amity Js SDK with NextJS, it must be imported using .

    • Chrome: 38+

    • Firefox: 42+

    • Microsoft Edge: 13+

    • Safari: 9+

    • Opera: 25+

    triangle-exclamation

    Amity Ts SDK probably won't work great in Internet Explorer 11. We generally support the recent versions of major browsers listed above.

    Since Amity Ts SDK uses local cache for performance and user experience reason, server side rendering is not supported. To use Amity Ts SDK with NextJS, it must be imported using .

    The minimum deployment target is:

    • iOS: iOS 9.0

    • Android: Android 4.4 (API Level 19)

    circle-info

    Use our TypeScript SDK natively to support your applications built using the React Native framework.

    The instructions for setting up your project will vary slightly, depending on your development environment. Refer this linkarrow-up-right to set up your project if you have not already done so.

    Logging out is a synchronous operation. Once the logout() function is called, the SDK disconnects from the server and wipes out user session.

    Androidarrow-up-right

    UIKit Open Source Repositories

    Our UIKit is ready to customize and use, the only task left for you is the integration. We make it as simple as that. Let's dig in!

    • iOSarrow-up-right

    • Androidarrow-up-right

    • JavaScriptarrow-up-right

    Region

    Endpoint

    Europe

    AmityRegion.EU

    Singapore

    AmityRegion.SG

    United States

    AmityRegion.US

    Android
    JavaScript
    TypeScript
    React Native
    Flutter
    Ionic
    Changelogs
    Amity Social Cloud Consolearrow-up-right
    Amity Social Cloud Console
    community.amity.coarrow-up-right
    Security page
    Session Handler
    herearrow-up-right
    iOSarrow-up-right
    Read morearrow-up-right
    Read morearrow-up-right
    Download our Developer Kitsarrow-up-right
    API key in Security page
    Locate your admin account and click on the three dots button (ellipsis) on the same line as your account.
  • From the dropdown menu, select "Admin Token."

  • This will provide you with the necessary 'Bearer' token to use for authorization when performing admin actions.

    makes the blocklisting more permissive and will block any occurrence of the blocklisted word or expression within a larger text.
    targetId is the identifier for the specific feed, such as a userId for a user feed or a communityId for a community feed.

    For a comprehensive explanation of these parameters and their usage, you can refer to the Amity SDK documentation on querying posts: https://docs.amity.co/amity-sdk/social/posts/query-post

    Using the SDK: If you’re utilizing the SDK, you can set the includeDelete: false parameter. This option allows you to control whether deleted communities are included in the query results. For more information on how to use this, visit Amity SDK - Query Communities https://docs.amity.co/amity-sdk/social/communities/query-communities and adjust the includeDelete parameter as needed.

    For Admin Users Using the Consolearrow-up-right: You can modify a user's role directly within the console. Follow these steps:
    1. Go to the specific community you wish to manage.

    2. Navigate to the 'Members' tab.

    3. Locate the user whose role you want to change.

    4. Click on the three dots button on the right-hand side.

    5. Select 'Change user role' from the options.

    Select "Communities."

  • Click on the name of the community you want to close.

  • Go to "Settings" page.

  • Scroll to the bottom where you will find the "Close Community" option.

  • Register/Unregister push notificationarrow-up-right

    and it still does't work. Ensure you’ve covered all bases in this checklist:

    • Verify that you’re using a production certificate.

    • Check if the app_id matches the issued push certificate.

    • Confirm the certificate hasn’t expired or been revoked.

    • Make sure the app enables the “push notification” capability.

    • Ensure the app is running in a production build (TestFlight/App Store).

    • Run the app on a real device.

    • Verify that the user hasn’t disabled push notifications for the app.

    • Check if the user’s “Do Not Disturb” mode is activated.

  • Amity UIKit iOS Changelogarrow-up-rightsarrow-up-right

  • Locate your admin account and click on the three dots button (ellipsis) on the same line as your account.
  • From the dropdown menu, select "Admin Token."

  • In the upper right corner you'll find a "Create Application" button.

    We recommend creating a separate application for each environment based on its specific purpose. This helps keep your testing and production environments organized and distinct.

    Your customer ID, which is an 8-digit number located on the left sidebar of the portal.

  • Specify the application ID that you intend to upgrade from. This should be your first application with the Basic plan.

  • Once you have gathered all the necessary information, please reach out to our support team at [email protected]envelope

    .
  • When retrieving the shared post, implement frontend logic to check for the presence of the "originalPostID" field in the metadata. If found, fetch the original post using the provided ID (e.g., by calling "get post") and display it on the frontend.

  • This approach enables you to maintain a reference to the original post, ensuring consistency in content, reactions, and comments.

    https://api-docs.amity.co/#/WebhookEventarrow-up-right

    To receive email notifications based on this webhook event, you may need to implement this functionality using a third-party tool that can send email notifications when the webhook event is triggered, such as when a post is flagged.

    size: This parameter specifies the maximum number of IDs to be returned in a single query.

    Please note that the maximum number of items returned per call is limited to 100.

    Adjust the confidence level in the console to an appropriate setting. For detailed instructions, please refer to this link: Image Moderation Settingsarrow-up-right.

  • If you are curious about how the confidence level functions and have questions, you can find answers in our FAQ section: Image Moderation FAQarrow-up-right.

  • Please be cautious not to set the confidence level too low, as it may result in the blocking of all images.

    For Chat Figma file: Amity Chat UI Kit Figmaarrow-up-right.
    Register a sessionarrow-up-right
    Amity consolearrow-up-right
    https://api-docs.amity.co/#/Network%20Setting/put_api_v3_network_settings_socialarrow-up-right
    https://api.amity.co/api/v3/files/{fileId}/download?size=fullarrow-up-right
    https://docs.amity.co/analytics-and-moderation/console/settings/security#secure-modearrow-up-right
    Query communities APIarrow-up-right
    Query communities APIarrow-up-right
    Add roles to community users APIarrow-up-right
    Delete community users APIarrow-up-right
    Delete Communityarrow-up-right
    APIarrow-up-right
    Amity consolearrow-up-right
    Join community APIarrow-up-right
    [email protected]envelope
    Custom post rankingarrow-up-right
    Push notification certificate setup arrow-up-right
    Amity SDK iOS Changelogsarrow-up-right
    iOS Push Notification Certificate Setuparrow-up-right
    Get poll answerarrow-up-right
    Amity consolearrow-up-right
    Amity portalarrow-up-right
    content searcharrow-up-right
    [email protected]envelope
    https://docs.amity.co/developers/beta-features/real-time-eventsarrow-up-right
    webhook eventsarrow-up-right
    consolearrow-up-right
    consolearrow-up-right
    Delete user APIarrow-up-right
    [email protected]envelope
    Amity Social UI Kit Figmaarrow-up-right
    {
      "paging": {
        "next": "eyJza2lwIjoyMCwibGltaXQiOjEwfQ=="
      },
    }
    curl --location --globoff 'https://api.sg.amity.co/api/v3/communities?filter=all&sortBy=lastCreated&options[token]=eyJza2lwIjoxMCwibGltaXQiOjEwfQ%3D%3D' \
    --header 'accept: application/json' \
    --header 'Authorization: Bearer xxx'
    curl --location 'https://api.sg.amity.co/api/v2/blacklist/records' \
    --header 'Content-Type: application/json' \
    --header 'Authorization: Bearer xxx' \
    --data '{
      "regexs": [
        "word1",
        "word2",
        "word3"
      ],
      "isMatchExactWord": true
    }'
    curl --location --request PUT 'https://api.sg.amity.co/api/v3/network-settings/social' \
    --header 'accept: application/json' \
    --header 'Content-Type: application/json' \
    --header 'Authorization: Bearer xxx' \
    --data '{
      "isFollowWithRequestEnabled": false
    }'

    Roles & Permissions

    AmityClient class provides a method hasPermission which allows you to check if the current logged in user has permission to do stuff in given channel.

    We determine a user's moderation capabilities based on their current role. Amity SDK has the following default roles:

    1. Member - has no moderation privileges

    client.unregisterSession();
    let client = try! AmityClient(apiKey: "api-key", region: .global)
    let endpoint = AmityEndpoint(httpUrl: "http-endpoint",
                                  rpcUrl: "rpc-endpoint",
                                mqttHost: "mqtt-host")
    let client = try! AmityClient(apiKey: "api-key", endpoint: endpoint)
    client.logout()
    client.disconnect()
    curl --location 'https://api.sg.amity.co/api/v3/communities?filter=all&isDeleted=false'
    --header 'accept: application/json'
    --header 'Authorization: Bearer xxx'
    curl --location 'https://api.sg.amity.co/api/v3/communities?filter=member' \
    --header 'accept: application/json' \
    --header 'Authorization: Bearer xxx'
    curl --location 'https://api.sg.amity.co/api/v4/communities/657306a3189cef362ea99923/users/roles' \
    --header 'accept: application/json' \
    --header 'Content-Type: application/json' \
    --header 'Authorization: Bearer xxx' \
    --data '{
      "roles": [
        "community-moderator"
      ],
      "userIds": [
        "test"
      ]
    }'
    {
      "apiKey": "xxx",
      "from": 0,
      "query": {
        "isDeleted": false,
        "targetId": [
          "test"
        ],
        "targetType": "community"
      },
      "size": 20,
      "sort": {
        "createdAt": {
          "order": "desc"
        }
      },
      "userId": "test"
    }
    "query": {
        "isDeleted": false
    }
    const [sessionState, setSessionState] = useState('');
    
    useEffect(() => {
      return Client.onSessionStateChange((state: Amity.SessionStates) => {
        setSessionState(state);
      });
    }, []);
    "paging": {
        "next": "string",
        "previous": "string"
    }
    curl --location --request DELETE 'https://api.sg.amity.co/api/v4/users/test2?deleteAll=true&markMessageDeleted=false&hardDeletePost=false&hardDeleteComment=false' \
    --header 'accept: application/json' \
    --header 'Authorization: Bearer xxx'

    Community/Channel Moderator - can assert general moderation privileges on other users

  • Super Moderator - can assert general moderation privileges and be exempt from moderation from other users

  • Global Admin (Admin Only) - can assign the roles of others, assert all moderation privileges and be exempt from moderation

  • A user's role can be changed via Console. Refer to Moderation, Roles & Privileges for the instructions on how to change a user's role.

    circle-exclamation

    The Global Admin role cannot be assigned to a user.

    Below are tables for each category that show the default roles and permissions. You can create new roles and assign a specific set of permissions for each role in the ASC Console. Refer to Moderation, Roles & Privileges.

    hashtag
    User

    Permission
    Global Admin
    Super Moderator
    Community Moderator
    Channel Moderator

    ASC Console Access

    ✅

    ✅

    ❌

    *UserV3

    hashtag
    Channel

    Permission
    Global Admin
    Super Moderator
    Community Moderator
    Channel Moderator

    Edit, Ban, Add, Remove, & Mute Channel User *

    ✅

    ✅

    ❌

    *ChannelV3

    hashtag
    Community

    Permission
    Global Admin
    Super Moderator
    Community Moderator
    Channel Moderator

    Create, delete, Edit Community Categories

    ✅

    ✅

    ✅

    *CommunityV3

    There is no limit to the number of moderators in a community. If there are 100 members in the community, all 100 members can be promoted to moderator. Promoting a user to a community-level moderator can be done using the Update Role APIarrow-up-right or through the SDK.

    hashtag
    User Feed, Posts, Comments, & Notifications

    Permission
    Global Admin
    Super Moderator
    Community Moderator
    Channel Moderator

    Edit & Delete User Feed Post

    ✅

    ✅

    ✅

    hashtag
    Permissions

    Each role can be assigned with many permissions. Below is a list of all the possible permissions that can be assigned to a user.

    Source

    Permission

    Description

    Channel

    MUTE_CHANNEL

    Can mute/unmute channel

    CLOSE_CHANNEL

    Dynamic Import with SSR disabledarrow-up-right
    Dynamic Import with SSR disabledarrow-up-right

    ❌

    Create, Edit, & Delete, Roles

    ✅

    ✅

    ✅

    ✅

    Ban & Edit User*

    ✅

    ❌

    ❌

    ❌

    Exempt from filters

    ✅

    ✅

    ❌

    ❌

    Exempt from rate limits

    ✅

    ✅

    ❌

    ❌

    Exempt from mute

    ✅

    ✅

    ❌

    ❌

    Exempt from ban

    ✅

    ✅

    ❌

    ❌

    Exempt from blacklist & whitelist

    ✅

    ✅

    ❌

    ❌

    Exempt from repitition check

    ✅

    ✅

    ❌

    ❌

    ✅

    Edit & Mute Channel*

    ✅

    ✅

    ❌

    ✅

    Edit & Delete Message*

    ✅

    ✅

    ❌

    ✅

    Edit Channel Rate Limit*

    ✅

    ❌

    ❌

    ❌

    Ban, Mute, Rate limit, & Manage Users

    ✅

    ✅

    ❌

    ✅

    Mute Channels

    ✅

    ✅

    ❌

    ✅

    Rate Limit Channels

    ✅

    ✅

    ❌

    ✅

    Manage Messages

    ✅

    ✅

    ❌

    ✅

    Global Access

    ✅

    ✅

    ❌

    ❌

    ❌

    Edit & Delete Communities*

    ✅

    ✅

    ✅

    ❌

    Edit, Add, Ban, & Remove Community Users*

    ✅

    ✅

    ✅

    ❌

    Edit, Delete, & Review Community Posts*

    ✅

    ✅

    ✅

    ❌

    Edit & Delete Community Comments*

    ✅

    ✅

    ✅

    ❌

    Manage Community

    ✅

    ✅

    ✅

    ❌

    Manage Community Stories

    ✅

    ✅

    ✅

    ❌

    ❌

    Edit & Delete User Feed Comment

    ✅

    ✅

    ✅

    ❌

    Manage Posts & Comments

    ✅

    ✅

    ✅

    ❌

    Manage Network Settings

    ✅

    ✅

    ✅

    ✅

    Can close channel

    EDIT_CHANNEL

    Can edit channel

    EDIT_CHANNEL_RATELIMIT

    Can set rate limit of channel

    EDIT_MESSAGE

    Can edit all messages

    DELETE_MESSAGE

    Can delete all messages

    BAN_CHANNEL_USER

    Can ban/unban user from channel

    MUTE_CHANNEL_USER

    Can mute/unmute user in channel

    ADD_CHANNEL_USER

    Can add users to channel

    REMOVE_CHANNEL_USER

    Can add remove user from channel

    EDIT_CHANNEL_USER

    Can edit users in channel

    User

    BAN_USER

    Can global ban/unban user

    EDIT_USER

    Can edit users

    ASSIGN_USER_ROLE

    Can assign role to users

    User feed

    EDIT_USER_FEED_POST

    Can edit all posts on user feed

    DELETE_USER_FEED_POST

    Can delete all posts in user feed

    EDIT_USER_FEED_COMMENT

    Can edit all comments on user feed

    DELETE_USER_FEED_COMMENT

    Can delete all comments in user feed

    Community

    ADD_COMMUNITY_USER

    Can add users to community

    REMOVE_COMMUNITY_USER

    Can remove users from community

    EDIT_COMMUNITY_USER

    Can edit users in community

    BAN_COMMUNITY_USER

    Can ban users in community

    MUTE_COMMUNITY_USER

    Can mute users in community

    EDIT_COMMUNITY

    Can edit community

    DELETE_COMMUNITY

    Can delete community

    EDIT_COMMUNITY_POST

    Can edit all posts in community feed

    DELETE_COMMUNITY_POST

    Can delete all posts in community feed

    EDIT_COMMUNITY_COMMENT

    Can edit all comments in community feed

    DELETE_COMMUNITY_COMMENT

    Can delete all comments in community feed

    REVIEW_COMMUNITY_POST

    Can review community post

    MANAGE_COMMUNITY_STORY

    Can create and delete community story

    Community Category

    CREATE_COMMUNITY_CATEGORY

    Can create new community categories

    EDIT_COMMUNITY_CATEGORY

    Can edit community categories

    DELETE_COMMUNITY_CATEGORY

    Can delete community categories

    Network

    CREATE_ROLE

    Can create new roles

    EDIT_ROLE

    Can edit roles

    DELETE_ROLE

    Can delete roles

    Notification

    MANAGE_NOTIFICATION_NETWORK_SETTING

    Can manage notification settings

    Create AmityFileRepository
    A login example
    With Auth Token
    Without Auth Token
    With Auth Token
    Without Auth Token
    Create Channel
    image-text
    image-text
    image-text
    Accessing live object properties