Let's integrate our SDK in few minutes

Chat SDKs for React Native#

CONTUS MirrorFly Chat SDK with its robust features and functionalities makes the integration more efficient and easy for every client’s app.

On client-side implementation, our chat SDK allows you to initialize and configure the chat easily. On server-side implementation, we ensure the most reliable infra-management services for the chat within the app.

This guided documentation here demonstrates the process as how to install the chat SDK in your app so that you can send and receive the messages without any interruption within a few simple steps.

note

CONTUS MirrorFly Chat SDKs use the fastest way in action, to experience the same you must use our trial app to enhance your existing chat app. So just download our sample app and make a start with your app development. Click here to download the sample app.

Requirements#

With MirrorFly React Native, make sure that you install all the below mentioned peer dependencies with their specific versions.

  • Node >= 18.20.4
  • npm - 10.7.0
  • react-native >= 0.73.0 <=0.75.4
Download media service files
Download

Media Service setup in Android#

Step 1: open your app-level build.gradle file located at: android/app/build.gradle, Inside the dependencies {} block, add the following dependencies:

dependencies {
implementation 'com.squareup.retrofit2:retrofit:2.1.0'
implementation 'com.google.code.gson:gson:2.6.2'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
}

Step 2: Download the Android file from the link above, locate the necessary Android files, and copy them into the android/app/src/main/java/com directory. Then, follow the steps below.

Step 3: Navigate to your Android project directory: android/app/src/main/java/com/yourpackage/, Create a new Kotlin file named MFModule.kt in this directory. Add the following code snippet to the file:

Note: Please ignore this if you already have MFModule.java or MFModule.kt. Otherwise, add the following line to the existing modules: MediaService(reactContext)

package com.YOURPACKAGE
import com.facebook.react.ReactPackage
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.uimanager.ViewManager
class MFModule : ReactPackage {
override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {
val modules: MutableList<NativeModule> = ArrayList()
modules.add(MediaService(reactContext))
return modules
}
override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
return emptyList()
}
}

Step 3: Download the above zip file and extract. Copy all the files inside the extracted folder and paste it inside project/android/app/src/main/java/com/[packageName]. After pasted all the files add the MFModule in MainApplication.kt file as mentioned in the below code snippet.

Note: Please ignore this if you already have.

class MainApplication : Application(), ReactApplication {
...
override val reactNativeHost: ReactNativeHost =
object : DefaultReactNativeHost(this) {
override fun getPackages(): List<ReactPackage> =
PackageList(this).packages.apply {
// Packages that cannot be autolinked yet can be added manually here, for example:
add(MFModule()) // <- Add this line
}
override fun getJSMainModuleName(): String = "index"
override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG
override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED
override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED
}
...
}

Media Service setup in iOS#

Step 1: Modify the Podfile: Open your Podfile located in the ios folder, and inside the target YOUR_TARGET do block, add the following dependency:

target 'YOUR_TARGET' do
# Add dependency
pod 'IDZSwiftCommonCrypto', '~> 0.13.0'
end

Step 2: Download the files from the link above, locate the necessary iOS files, and add them using Add Files to [Your Project] in Xcode. Then, follow the steps below

Step 3: If you are already using the bridge header, you can skip this setup. Otherwise, please create a bridge header, Steps to Create a Bridging Header in Xcode

  1. Open Your Xcode Project

    In your React Native project, navigate to the ios folder and open the .xcworkspace file in Xcode.

  2. Add a New Swift File

    In Xcode, go to File → New → File.

    Select Swift File under the Source section and click Next.

    Name the file (e.g., Dummy.swift).

    Click Create.

  3. Automatic Pop-up for Bridging Header

    When you create the Swift file, a pop-up will appear asking: "Would you like to configure an Objective-C bridging header?"

    alt text

    Click "Create Bridging Header".

    Xcode will automatically generate a file named:

    YourProjectName-Bridging-Header.h

Things To Be Noted Before You Get Started#

SDK License Key#
caution

Skip this part if you are already having your license key.

To integrate MirrorFly Chat SDK into your app, you will need a SDK License Key. The MirrorFly server will use this license key to authenticate the SDK in your application.

To get the License Key,#

Step 1: Register here to get a MirrorFly User account. Registration is subject to verification and would take up to 24 hours.

Step 2: Login to your Account

Step 3: Get the License key from the application Info’ section

license-key

Integrate the Chat SDK#

Step 1: Update all your packages.json files.

Step 2: Check your packages files have any duplicate if it is not working in iOS.

Integrate Using Npm package#

note

Install mirrorfly-reactnative-sdk (https://www.npmjs.com/package/mirrorfly-reactnative-sdk) npm package by using the below command

Step 3: Install Mirrorfly Sdk in your application

npm i mirrorfly-reactnative-sdk

Step 4: Import the SDK into your application where you want

import { SDK } from "mirrorfly-reactnative-sdk";

Adding NPM package dependencies to Integrate the Chat SDK#

{
'@react-native-community/netinfo' : '^11.4.1',
"react-native-get-random-values": "1.11.0", //must use version >=1.7.1
'realm': "^20.1.0",
'react-native-fs': "^2.20.0",
'moment': "2.30.1",
//add the below calls related dependencies
"react-native-webrtc": "124.0.4" // must use version "124.0.4"
"react-native-background-timer": "^2.4.1",
'react-native-permissions':'^5.2.1'
}

Initialize Chat SDK#

To begin with the initialization process of the chat SDK you are required to have certain data that responds to the changes in the connection status in the client's app.

Now, paste the license key on the licensekey param and use the below given method to pass these data through the SDK for further processing.

In your App file (e.g., App.tsx or App.js), import the SDK and call the initializeSDK function with the appropriate parameters:

note

You can find the sandbox server details in the further Sandbox section for testing purposes.

const initializeObj = {
apiBaseUrl: `API_URL`,
licenseKey: `LICENSE_KEY`,
isTrialLicenseKey: `TRIAL_MODE`,
callbackListeners: {},
};
await SDK.initializeSDK(initializeObj);

Request Params#

ArgumentsDescriptionTypeRequired
apiBaseUrlAPI Base URL for BackendStringtrue
licenseKeyMirrorfly's License KeyStringtrue
isTrialLicenseKeyif true Trial Mode will be EnabledBooleanfalse
callbackListenersCheck here for callback listernersObjecttrue

Response Params#

ArgumentsDescriptionType
statusCodeStatus CodeNumber
messageSuccess/Error MessageString

Sandbox Details#

The apiUrl and licenseKey details can get it from the 'Overview' section in the mirrorfly Console dashboard.

license-key

function connectionListener(response) {
if (response.status === "CONNECTED") {
console.log("Connection Established");
} else if (response.status === "DISCONNECTED") {
console.log("Disconnected");
}
}
const initializeObj = {
apiBaseUrl: "https://api-preprod-sandbox.mirrorfly.com/api/v1",
licenseKey: "XXXXXXXXXXXXXXXXX",
isTrialLicenseKey: true,
callbackListeners: {
connectionListener
},
};
await SDK.initializeSDK(initializeObj);
note

To learn more about callback listeners, go to the Callback Event Listener Section.

Example Response#

{
"statusCode": 200,
"message": "Success"
}

Register User#

Step 1: You can use the below given method to register a new user.

Step 2: Once you are registered, you will be provided with a username and password that you can utilize to make the connection with the server via connect method.

await SDK.register(USER_IDENTIFIER, FCE_TOKEN, VOIP_DEVICE_TOKEN, MODE, REGISTER_META_DATA, FORCE_REGISTER);

Request Params#

StatusDescriptionTypeRequired
USER_IDENTIFIERUnique Id to Register the User. SDK only accepts the AlphaNumeric String, hyphens(-) and underscores(_)Stringtrue
FCE_TOKENA registration token that is generated by FCM SDK for the user's app instance to send message for freeStringtrue
VOIP_DEVICE_TOKENToken to register VoIP device (optional)Stringtrue
MODEDetermines the build environment for VoIP push notifications. Set to true in production mode and false in development mode.Stringtrue
REGISTER_META_DATAlist of key - value pair of metadata object. Maximum size is 3Stringtrue
FORCE_REGISTERdefault value true provide true to force the logout of the old session If the registered user has reached the maximum no of multi-sessions or provide false to allow registration till the maximum no of multi-sessionsStringtrue
KeywordDescription
USER_IDENTIFIERUnique ID assigned for each user Ex: 12345678 (any alphanumeric). The below characters is not allowed in userId: U+0022 (") U+0026 (&) U+0027 (') U+002F (/) U+003A (:) U+003C (<) U+003E (>) U+0040 (@) userID should follow below specification: https://xmpp.org/extensions/xep-0106.html

Response Params#

ArgumentsDescriptionType
statusCodeStatus CodeNumber
messageSuccess/Error MessageString
dataUsername and PasswordObject

Sample Response:#

{
statusCode: 200,
message: "Success",
data: {
username: "123456789",
password: "987654321"
}
}
caution

username is the unique id that allows you to connect with other users to send or receive messages.

Connect to MirrorFly Server#

Step 1: You can use the credentials that you have obtained while registration to make the connection with the server.

Step 2: Once you have created the connection successfully, you will be responded with an approval message as ‘statusCode of 200’ or else will get an execution error.

Step 3: With this you can also trace the connection status that you receive in connectionListener callback function.

Step 4: If you face any error while making a connection with the server, you will receive an error message with callback.

await SDK.connect(`USERNAME`, `PASSWORD`);

Request Params#

StatusDescriptionTypeRequired
USERNAMEUsernameStringtrue
PASSWORDPasswordStringtrue

Response Params#

ArgumentsDescriptionType
statusCodeStatus CodeNumber
messageSuccess/Error MessageString

Sample Response:#

{
message: "Login Success",
statusCode: 200
}
note

To learn more about all possible logins and profile related setup, go to Profile Section.

Send a Message#

Finally, to send a message to another user you can use the below given method,

note

You can use the const userJid = SDK.getJid(USER_ID) method, to generate a JID for any user.

await SDK.sendTextMessage(`TO_USER_JID`, `MESSAGE_BODY`,`MESSAGE_ID`,`REPLY_TO`);

Request Param#

StatusDescriptionTypeRequired
TO_USER_JIDJID of the To User. username + "@" + xmppSocketHostJID Stringtrue
MESSAGE_BODYText Message BodyStringtrue
MESSAGE_IDText Message IdStringtrue
REPLY_TOSpecifies the Message ID of replied message (Optional)Stringtrue

Response Params#

ArgumentsDescriptionType
statusCodeStatus CodeNumber
messageSuccess/Error MessageString

Response Format:#

{
"message": "",// String - Success/Error Message
"statusCode": "" // Number - status code
}

Receive a Message#

To receive a message from another user you must implement the messageListener function. It’s a function that will be triggered whenever you receive a new message or related event in one-to-one or group chat. Further to initialize the SDK, you need to add the below callback method during the process.

function messageListener(response) {
console.log("Message Listener", response);
}
note

To learn more on 'message listener callbacks,' see the Message Callback Event Listener Section