tencent cloud

Feedback

React Native

Last updated: 2024-09-13 14:27:00
    This document describes how to quickly integrate the Tencent Cloud Chat SDK into your React Native project.
    Note:
    1. Integrating @tencentcloud/chat into your React Native project requires downloading version 3.4.3 or later.
    2. Integrating tim-upload-plugin into your React Native project requires downloading version 1.4.0 or later.

    Environment Requirements

    Platform
    Version
    React Native
    v0.75.0 or later.
    Android
    Android Studio 3.5 or later. The app requires Android 4.1 or later devices.
    iOS
    Xcode 11.0 or later. For testing with a real device, make sure that your project has a valid developer signature.
    Node
    Version 18.0 or later.

    Configuring the development environment

    If this is your first time developing a React Native project, refer to the React Native official steps set-up-your-environment to configure the development environment.
    If you encounter environment problems when creating or compiling the project, you can run npx react-native doctor for environment diagnostics.

    Create a project (can be skipped if you already have one)

    npx react-native@latest init chatExample
    npm react-native creates projects with Android gradle version 8.8. If your Android gradle version is lower than 8.8, please open Android Studio to sync the gradle version.

    Integrate Chat SDK

    Integrate the Chat SDK into your React Native project using npm.
    You can integrate the upload plugin tim-upload-plugin for faster and safer upload of rich text message resources.
    Enhance the user experience in a poor network environment or during network switching by integrating @react-native-community/netinfo.
    Install the Chat SDK dependencies in your React Native project.
    npm install @tencentcloud/chat tim-upload-plugin @react-native-community/netinfo --save

    Initialization

    You must have the correct SDKAppID to proceed with the initialization. SDKAppID is the unique identifier Tencent Cloud IM uses to distinguish customer accounts. We recommend applying for a new SDKAppID for each independent app. Messages between different SDKAppIDs are inherently isolated and cannot be interoperated. You can view all SDKAppIDs in the Chat console. Click Create application to create a new SDKAppID.
    
    Import the Chat SDK and initialize it in your project's App.tsx.
    import TencentCloudChat from '@tencentcloud/chat';
    import TIMUploadPlugin from 'tim-upload-plugin';
    import NetInfo from '@react-native-community/netinfo';
    
    let options = {
    SDKAppID: 0 // Replace 0 with the SDKAppID of your Chat application when connecting
    };
    // Create an SDK instance. The `TencentCloudChat.create()` method returns the same instance for the same `SDKAppID`
    let chat = TencentCloudChat.create(options); // The SDK instance is usually referred to as chat
    
    chat.setLogLevel(0); // Normal level, with a lot of logs; it's recommended for integration
    
    // Register the Tencent Cloud Instant Messaging rich media resource upload plugin
    chat.registerPlugin({'tim-upload-plugin': TIMUploadPlugin});
    // Register the network monitoring plugin
    chat.registerPlugin({'chat-network-monitor': NetInfo});

    Listening on events

    SDK_READY

    This is triggered when the SDK enters the ready state. After the accessing side listens to this event, it can call SDK APIs to send messages or use other SDK features.
    let onSdkReady = function(event) {
    // After listening to the SDK ready event, you can make API calls
    };
    chat.on(TencentCloudChat.EVENT.SDK_READY, onSdkReady);

    SDK_NOT_READY

    This is triggered when the SDK enters the not-ready state. At this time, the accessing side will not be able to use features like sending messages via the SDK. To resume usage, the accessing side needs to call the login interface and drive the SDK to enter the ready state.
    let onSdkNotReady = function(event) {
    // chat.login({userID: 'your userID', userSig: 'your userSig'});
    };
    chat.on(TencentCloudChat.EVENT.SDK_NOT_READY, onSdkNotReady);

    MESSAGE_RECEIVED

    When the SDK receives new messages from one-on-one chat, group chat, group prompts, or group system notifications, the accessing side can traverse event.data to obtain the message list data and render it to the UI.
    let onMessageReceived = function(event) {
    // event.data - An array that stores `Message` objects - [Message]
    };
    chat.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, onMessageReceived);

    CONVERSATION_LIST_UPDATED

    The conversation list is updated. event.data is an array containing Conversation objects.
    let onConversationListUpdated = function(event) {
    console.log(event.data); // Array that stores Conversation instances
    };
    chat.on(TencentCloudChat.EVENT.CONVERSATION_LIST_UPDATED, onConversationListUpdated);
    Note:
    If you need to learn more about SDK event notifications, please view the SDK event list.

    Deinitialization

    Terminate the SDK instance. The SDK will log out, disconnect the WebSocket persistent connection, and then release resources.
    chat.destroy();

    Login

    Log in requires providing information such as userID and userSig. Please log in to the Chat console to obtain them.
    userID
    Click to enter the Application you created, and you will see the Chat Product entry in the left sidebar. Click to enter.
    After entering the Chat Product subpage, click Users to enter the user management page.
    Click Create account to pop up the account creation information form. If you are a regular member, we recommend choosing the General type.
    To enhance your experience with message sending and receiving features, we recommend creating two userIDs.
    
    userSig can be generated in real-time using the development tools provided by the console. Please click Chat Console > Development Tools > UserSig Tools > Signature (UserSig) Generator.
    
    let promise = chat.login({
    userID: 'your userID',
    userSig: 'your userSig',
    });
    promise.then(function(imResponse) {
    if (imResponse.data.repeatLogin === true) {
    // This indicates that the account is already logged in. This login attempt is a duplicate login.
    console.log(imResponse.data.errorInfo);
    }
    }).catch(function(imError) {
    // Information related to login failure
    console.warn('login error:', imError);
    });

    Compile and run the React Native application

    To compile and run the project, you need to use a real device or an emulator.A real device is recommended. You can refer to the React Native official websiterunning-on-deviceto connect a real device for debugging.
    Android
    iOS
    1. Enable Developer Mode on your phone, and turn on theUSB Debugging switch.
    2. Connect your phone via USB. It's recommended to select the Transfer files option, do not choose the Charging only option.
    3. After confirming the successful connection of your phone, executenpm run androidto compile and run the project.
    npm run android
    1. Connect your mobile phone with a USB cable, and open the ios directory of the project using Xcode.
    2. Configure the signing information according to the React Native official websiterunning-on-device.
    3. Go to the ios directory and install dependencies.
    cd ios
    pod install
    4. Go back to the root directory and executenpm run iosto compile and run the project.
    cd ../
    npm run ios

    FAQs

    1. When running npm run android and encountering the error shown in the image, please reset the environment variables in the root directory of the project.
    
    export ANDROID_HOME=$HOME/Library/Android/sdk export PATH=$PATH:$ANDROID_HOME/emulator export PATH=$PATH:$ANDROID_HOME/platform-tools
    2. If you encounter node environment variable issues when executing the Build command in Xcode, please perform the following steps:
    
    cd ios
    echo export NODE_BINARY=$(command -v node) > .xcode.env

    Documentation

    For more information on Chat SDK APIs, please refer to the Client API.
    
    
    Contact Us

    Contact our sales team or business advisors to help your business.

    Technical Support

    Open a ticket if you're looking for further assistance. Our Ticket is 7x24 avaliable.

    7x24 Phone Support