### Install CometChat iOS UI Kit Dependencies
Source: https://www.cometchat.com/docs/ui-kit/react/overview/ui-kit/ios/getting-started
Learn to integrate CometChat UI Kit and core Chat SDK into your iOS project using CocoaPods or Swift Package Manager. This guide provides commands for setup, dependency declaration, and updates.
```Swift
pod init
```
```Swift
platform :ios, '13.0'
use_frameworks!
target 'YourApp' do
# CometChat UI Kit for Swift
pod 'CometChatUIKitSwift', '5.0.4'
# Optional: Include if you're using Audio/Video Calling
pod 'CometChatCallsSDK', '4.1.2'
end
```
```Swift
pod install
```
```Swift
pod install --repo-update
```
```Swift
pod update CometChatUIKitSwift
```
```Swift
pod update CometChatCallsSDK
```
```Swift
https://github.com/cometchat/cometchat-uikit-ios
```
```Swift
5.0.4
```
```Swift
https://github.com/cometchat/chat-sdk-ios
```
```Swift
4.0.61
```
--------------------------------
### Install CometChat UI Kit and Core Dependencies for React Native
Source: https://www.cometchat.com/docs/ui-kit/react/overview/ui-kit/react-native/getting-started
These commands install the main CometChat UI Kit package along with all necessary supplementary packages. This includes the core CometChat SDK, and various React Native community libraries required for full UI Kit functionality such as datetimepicker, clipboard, SVG, video, dayjs, and async storage.
```Bash
npm i @cometchat/chat-uikit-react-native
```
```Bash
npm i @cometchat/chat-sdk-react-native
npm i @react-native-community/datetimepicker
npm i @react-native-clipboard/clipboard
npm i react-native-svg
npm i react-native-video
npm i dayjs
npm i @react-native-async-storage/async-storage
```
--------------------------------
### CometChat iOS UI Kit Development Environment Requirements
Source: https://www.cometchat.com/docs/ui-kit/react/overview/ui-kit/ios/getting-started
Outlines the necessary development environment specifications for integrating the CometChat iOS UI Kit. Ensure your system meets these prerequisites for successful setup and compilation.
```APIDOC
System Requirements for iOS UI Kit Development:
- "Xcode": {
"version": "16 or later",
"description": "Integrated Development Environment for Apple platforms."
},
- "iOS Device or Simulator": {
"version": "iOS 13.0 or above",
"description": "Target device or simulator operating system version."
},
- "Swift": {
"version": "5.0",
"description": "Programming language version."
},
- "Operating System": {
"platform": "macOS",
"description": "Required operating system for development."
}
```
--------------------------------
### Install and Configure CometChat Calls SDK for React Native
Source: https://www.cometchat.com/docs/ui-kit/react/overview/ui-kit/react-native/getting-started
This section details the optional installation and configuration of the CometChat Calls SDK for React Native applications. It includes commands to install the SDK via npm, a list of required dependencies, and the necessary Android and iOS permissions for calling functionality. Ensure all dependencies are met and permissions are added for successful call integration.
```Bash
npm i @cometchat/calls-sdk-react-native
```
```JSON
{
"@cometchat/chat-sdk-react-native": "^4.0.5",
"@react-native-async-storage/async-storage": "^1.17.5",
"@react-native-community/netinfo": "7.1.7", // for react-native 0.63 & above.
"@react-native-community/netinfo": "6.1.0", // for react-native below 0.63
"react-native-background-timer": "2.4.1",
"react-native-callstats": "3.73.7",
"react-native-webrtc": "1.106.1"
}
```
```XML
```
```XML
NSCameraUsageDescription
This is for Camera permission
NSMicrophoneUsageDescription
This is for Mic permission
```
--------------------------------
### Install CometChat UI Kit React Dependencies
Source: https://www.cometchat.com/docs/ui-kit/react/overview/ui-kit/react/react-js-integration
This snippet provides the command-line instructions to install the CometChat UI Kit for React. Installing this package automatically includes the core CometChat JavaScript SDK, simplifying integration. You can choose between npm or Yarn based on your project's preferred package manager. Execute these commands from your project's root directory.
```Shell
npm install @cometchat/chat-uikit-react
```
```Shell
yarn add @cometchat/chat-uikit-react
```
--------------------------------
### Initialize a React Project with Vite or Create React App
Source: https://www.cometchat.com/docs/ui-kit/react/overview/ui-kit/react/react-js-integration
This snippet demonstrates how to initialize a new React project using either Vite (recommended for faster development) or Create React App. It provides the necessary command-line instructions to create the project and navigate into its directory, setting up a TypeScript-enabled React environment. Ensure Node.js and a package manager like npm or Yarn are installed on your system.
```Shell
npm create vite@latest my-app --template react-ts
cd my-app
```
```Shell
npx create-react-app my-app --template typescript
cd my-app
```
--------------------------------
### Configure and Run CometChat React App for Preview
Source: https://www.cometchat.com/docs/ui-kit/react/overview/ui-kit/react/builder-integration-react-router
This snippet guides you through setting up and running the CometChat React sample application for previewing customizations. It requires you to replace placeholder credentials (App ID, Region, Auth Key) in `src/index.tsx` and then install dependencies and start the development server using npm commands. This allows for local testing of the chat experience before full integration.
```TypeScript
export const COMETCHAT_CONSTANTS = {
APP_ID: "", // Replace with your App ID
REGION: "", // Replace with your App Region
AUTH_KEY: "", // Replace with your Auth Key or leave blank if you are authenticating using Auth Token
};
```
```bash
npm i
```
```bash
npm start
```
--------------------------------
### Install CometChatSDK Framework via CocoaPods
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/ios/setup
Execute this command in your terminal to download and integrate the CometChatSDK and its dependencies into your iOS project. This step compiles the SDK and links it with your application.
```Swift
$ pod install
```
--------------------------------
### Install CometChat Ionic SDK Dependency
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/ionic/setup
This command installs the CometChat Chat SDK for Ionic as an NPM module. It is a prerequisite for integrating CometChat functionalities into your Ionic application. Ensure Node.js and npm are installed before running this command.
```Javascript
npm install @cometchat/chat-sdk-ionic
```
--------------------------------
### Install CometChat JavaScript SDK via NPM
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/javascript/setup-sdk
This snippet demonstrates how to install the CometChat JavaScript SDK using npm, the Node.js package manager. It adds the necessary dependency to your project, allowing you to import and use CometChat functionalities.
```JavaScript
npm install @cometchat/chat-sdk-javascript
```
--------------------------------
### CometChat SDK Initialization API Reference
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/android/setup
Detailed API reference for the CometChat.init() method and the AppSettings class, including parameters, properties, and their descriptions for initializing the CometChat SDK.
```APIDOC
CometChat.init(context, appID, appSettings, callbackListener):
Parameters:
- context: Android context for your application
- appID: Your CometChat App ID
- appSettings: An object of the AppSettings class.
- callbackListener: A CometChat.CallbackListener to handle success or error.
AppSettings Class:
Properties:
- Region (string): The region where your app was created (e.g., "eu", "us").
- Presence Subscription (enum/type): Represents the subscription type for user presence (real-time online/offline status).
- autoEstablishSocketConnection (boolean): If true, SDK manages the web-socket connection internally. Default is true. If false, connection is managed manually.
- overrideAdminHost(adminHost: string): Overrides the default admin URL with the provided adminHost. Useful for dedicated deployments.
- overrideClientHost(clientHost: string): Overrides the default client URL with the provided clientHost. Useful for dedicated deployments.
```
--------------------------------
### Install CometChat React Native SDK
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/react-native/setup-sdk
Install the CometChat React Native SDK as an NPM module. This is the primary dependency for integrating CometChat chat functionalities into your React Native application.
```Javascript
npm i @cometchat/chat-sdk-react-native
```
--------------------------------
### Swift: Initialize and Login CometChat UI Kit
Source: https://www.cometchat.com/docs/ui-kit/react/overview/ui-kit/ios/getting-started
This Swift code snippet demonstrates the initialization of the CometChat UI Kit and user login within a `SceneDelegate.swift` file. It shows how to configure `UIKitSettings` with App ID, Region, and Auth Key, then proceeds to log in a user with a specified UID. The snippet includes success and error handling for both initialization and login, along with commented-out examples for launching different chat views.
```Swift
import UIKit
import CometChatUIKitSwift
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = (scene as? UIWindowScene) else { return }
let uikitSettings = UIKitSettings()
.set(appID: "<#Enter Your App ID Here#>")
.set(region: "<#Enter Your Region Code Here#>")
.set(authKey: "<#Enter Your AuthKey Here#>")
.subscribePresenceForAllUsers()
.build()
CometChatUIKit.init(uiKitSettings: uikitSettings) { result in
switch result {
case .success:
debugPrint("CometChat UI Kit initialization succeeded")
let uid = "cometchat-uid-1"
CometChatUIKit.login(uid: uid) { loginResult in
switch loginResult {
case .success:
debugPrint("CometChat UI Kit login succeeded")
// ✅ Option 1: Launch One-to-One or Group Chat Screen
// DispatchQueue.main.async {
// self.setUpOneOneOrGroupConversation(windowScene: windowScene, uid: "cometchat-uid-2")
// }
// ✅ Option 2: Launch Conversation List + Message View (Split-Screen Style)
// DispatchQueue.main.async {
// self.setupConversationsView(windowScene: windowScene)
// }
// ✅ Option 3: Launch Tab-Based Chat Experience (Chats, Calls, Users, Groups)
// DispatchQueue.main.async {
// self.setupTabbedView(windowScene: windowScene)
// }
case .onError(let error):
debugPrint("CometChat UI Kit login failed with error: \(error.description)")
@unknown default:
break
}
}
case .failure(let error):
debugPrint("CometChat UI Kit initialization failed with error: \(error.localizedDescription)")
}
}
}
}
```
--------------------------------
### Install CometChatCalls SDK and Import Class
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/javascript/calling-setup
This snippet demonstrates how to install the CometChatCalls SDK using either npm or yarn, and then how to import the `CometChatCalls` class into your JavaScript or TypeScript application. This is a crucial step for initializing and utilizing the SDK's calling functionalities.
```npm
npm install @cometchat/calls-sdk-javascript
```
```yarn
yarn add @cometchat/calls-sdk-javascript
```
```JavaScript
import { CometChatCalls } from "@cometchat/calls-sdk-javascript";
```
```TypeScript
import { CometChatCalls } from "@cometchat/calls-sdk-javascript";
```
--------------------------------
### Install CometChat UI Kit React Dependencies via npm
Source: https://www.cometchat.com/docs/ui-kit/react/overview/ui-kit/react/react-router-integration
This `npm` command installs the `@cometchat/chat-uikit-react` package, which is an extension of the CometChat JavaScript SDK. Installing this package automatically includes the core Chat SDK, providing all necessary dependencies for integrating CometChat's UI components and chat functionalities into your React application.
```bash
npm install @cometchat/chat-uikit-react
```
--------------------------------
### CometChat APIs Overview
Source: https://www.cometchat.com/docs/ui-kit/react/overview/ui-kit/flutter/getting-started
Overview of CometChat's Chat and Management APIs, providing programmatic control over chat functionalities and application management.
```APIDOC
{
"APIs": [
{
"name": "Chat APIs",
"description": "Connect CometChat with your app and programatically manage users, groups and conversations.",
"reference_url": "https://api-explorer.cometchat.com/reference/chat-apis"
},
{
"name": "Management APIs",
"description": "Create and manage your CometChat apps, trigger webhooks and access dashboard features.",
"reference_url": "https://api-explorer.cometchat.com/reference/management-apis"
}
]
}
```
--------------------------------
### Initialize CocoaPods Podfile for iOS Project
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/ios/setup
This command creates a new `Podfile` in your project directory, which is essential for managing dependencies with CocoaPods. Run this command from your project's root directory in the terminal.
```Swift
$ pod init
```
--------------------------------
### CometChat Sample Applications
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/android/retrieve-groups
Access ready-to-use sample applications demonstrating CometChat integration across various platforms. These examples provide a quick start for developers to understand implementation patterns.
```APIDOC
React Chat App: Sample application demonstrating CometChat UI Kit integration in React. Available at https://github.com/cometchat/cometchat-uikit-react/tree/v6/sample-app
```
```APIDOC
React Native Chat App: Sample application demonstrating CometChat integration in React Native. Available at https://github.com/cometchat-pro/cometchat-chat-sample-app-react-native
```
```APIDOC
iOS Chat App: Sample application demonstrating CometChat integration in iOS (Swift). Available at https://github.com/cometchat/cometchat-sample-app-ios/tree/v5
```
```APIDOC
Android Chat App (Java): Sample application demonstrating CometChat UI Kit integration in Android (Java). Available at https://github.com/cometchat/cometchat-uikit-android/tree/v5/sample-app-java
```
```APIDOC
Android Chat App (Kotlin): Sample application demonstrating CometChat UI Kit integration in Android (Kotlin). Available at https://github.com/cometchat/cometchat-uikit-android/tree/v5/sample-app-kotlin
```
--------------------------------
### Install Firebase SDK with npm
Source: https://www.cometchat.com/docs/ui-kit/react/overview/notifications/legacy-push-notifications
This snippet demonstrates how to install the Firebase SDK using npm for web applications. It's a prerequisite for using Firebase services in your project.
```npm
npm install firebase
```
--------------------------------
### Load CometChat Conversations Component in React Native
Source: https://www.cometchat.com/docs/ui-kit/react/overview/ui-kit/react-native/getting-started
This React Native code snippet initializes the CometChat UI Kit and logs in a demo user, then renders the `CometChatConversations` component. It dynamically switches between displaying the conversation list and an active chat screen based on user selection. The example requires `@cometchat/chat-uikit-react-native` and `@cometchat/chat-sdk-react-native` dependencies.
```TypeScript
import React, { useEffect, useState } from "react";
import { SafeAreaView, ViewStyle } from "react-native";
import {
CometChatConversations,
CometChatUIKit,
CometChatUiKitConstants,
UIKitSettings,
CometChatThemeProvider,
} from "@cometchat/chat-uikit-react-native";
import { CometChat } from "@cometchat/chat-sdk-react-native";
import Messages from "./src/components/Messages";
/* -------------------------------------------------------------------------- */
/* ⚙️ Replace the placeholders below with your own CometChat credentials. */
/* -------------------------------------------------------------------------- */
const APP_ID = ""; // e.g. "123456abc"
const AUTH_KEY = ""; // e.g. "0b1c2d3e4f5g6h7i8j9k"
const REGION = ""; // e.g. "us" | "eu" | "in"
const DEMO_UID = ""; // e.g. "john_doe"
/* -------------------------------------------------------------------------- */
/**
* App
* ---
* The root component:
* 1. Initializes the CometChat UI Kit.
* 2. Logs a demo user in.
* 3. Shows either the conversation list or an active chat screen.
*/
const App = (): React.ReactElement => {
/* ------------------------------------------------------------------ */
/* Local state */
/* ------------------------------------------------------------------ */
const [loggedIn, setLoggedIn] = useState(false);
const [messageUser, setMessageUser] = useState();
const [messageGroup, setMessageGroup] = useState();
/* ------------------------------------------------------------------ */
/* One-time initialization */
/* ------------------------------------------------------------------ */
useEffect(() => {
const init = async () => {
// 1️⃣ Configure the UI Kit.
const uiKitSettings: UIKitSettings = {
appId: APP_ID,
authKey: AUTH_KEY,
region: REGION,
subscriptionType: CometChat.AppSettings
.SUBSCRIPTION_TYPE_ALL_USERS as UIKitSettings["subscriptionType"],
};
try {
await CometChatUIKit.init(uiKitSettings);
console.log("[CometChatUIKit] initialized");
// 2️⃣ Login.
await CometChatUIKit.login({ uid: DEMO_UID });
setLoggedIn(true);
} catch (err) {
console.error("[CometChatUIKit] init/login error", err);
}
};
init();
}, []);
/* ------------------------------------------------------------------ */
/* Render */
/* ------------------------------------------------------------------ */
return (
{/* Show conversations only after the user is logged in */}
{loggedIn && (
<>
{/* Conversation list (hidden when a chat is open) */}
{
if (
conversation.getConversationType() ===
CometChatUiKitConstants.ConversationTypeConstants.user
) {
setMessageUser(
conversation.getConversationWith() as CometChat.User
);
return;
}
setMessageGroup(
conversation.getConversationWith() as CometChat.Group
);
}}
/>
{/* Active chat screen */}
{(messageUser || messageGroup) && (
{
setMessageUser(undefined);
setMessageGroup(undefined);
}}
/>
)}
>
)}
);
};
/* -------------------------------------------------------------------------- */
/* Styles */
/* -------------------------------------------------------------------------- */
const styles: { fullScreen: ViewStyle } = {
fullScreen: { flex: 1 },
};
export default App;
```
--------------------------------
### Configure iOS Permissions and Target Version for CometChat Calls
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/react-native/calling-setup
Add camera and microphone usage descriptions to your Info.plist file to ensure proper access. Update the minimum iOS platform version to 12.0 in your Podfile and run 'pod install' from the 'ios/App' folder to complete the setup for iOS.
```XML
NSCameraUsageDescription
This is for Camera permission
NSMicrophoneUsageDescription
This is for Mic permission
```
```Ruby
platform :ios, '12.0'
```
--------------------------------
### Configure Dependencies for CometChat Calling Component
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/react-native/setup-sdk
Add necessary dependencies for the CometChat Calling component in your `package.json`. These packages enable real-time audio/video calling features within your React Native application.
```JSON
{
"@cometchat/chat-sdk-react-native": "^4.0.12",
"@react-native-async-storage/async-storage": "^1.23.1",
"@react-native-community/netinfo": "^11.3.1",
"@react-native-community/netinfo": "6.1.0",
"react-native-background-timer": "^2.4.1",
"react-native-callstats": "^3.73.7",
"react-native-webrtc": "^1.106.1"
}
```
--------------------------------
### CometChat `init()` Method and `AppSettings` API Reference
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/javascript/setup-sdk
Detailed API documentation for the `CometChat.init()` method and the `AppSettings` class, including parameters, properties, and their descriptions. This reference covers configuration options for CometChat SDK initialization.
```APIDOC
CometChat.init(appID: string, appSettings: CometChat.AppSettings): Promise
Description: Initializes the settings required for CometChat. Must be called before any other CometChat method.
Parameters:
- appID (string): Your CometChat App ID.
- appSettings (CometChat.AppSettings): An object of the AppSettings class, created using AppSettingsBuilder.
AppSettings Class Properties:
- Region (string): The region where your app was created. (Mandatory, set via setRegion())
- Presence Subscription (string): Represents the subscription type for user presence (real-time online/offline status).
- autoEstablishSocketConnection (boolean): Manages web-socket connection internally (true) or manually (false). Default: true.
- overrideAdminHost(adminHost: string): Uses the provided admin URL instead of the default admin URL.
- overrideClientHost(clientHost: string): Uses the provided client URL instead of the default client URL.
Return Value: Promise
```
--------------------------------
### Install Async-Storage Dependency for React Native
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/react-native/setup-sdk
Install the Async-Storage dependency, which is required for the CometChat React Native SDK to function correctly, especially for persistent data storage.
```Javascript
npm install @react-native-async-storage/async-storage
```
--------------------------------
### Install CometChat Ionic SDK via NPM
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/ionic/overview
This snippet demonstrates how to add the CometChat Ionic SDK to your project by installing it as an NPM module. This is the first step to integrate CometChat's real-time chat functionalities into your Ionic application. Ensure you have Node.js and npm installed.
```JavaScript
npm install @cometchat/chat-sdk-ionic
```
--------------------------------
### Run React Development Server with npm
Source: https://www.cometchat.com/docs/ui-kit/react/overview/ui-kit/react/v5/integration
This snippet provides the standard command to start the React development server. After configuring the CometChat UI Kit and integrating its components, executing `npm start` will launch your application locally. This allows you to preview and test the integrated CometChat features in your browser.
```Shell
npm start
```
--------------------------------
### Create a new React Native project
Source: https://www.cometchat.com/docs/ui-kit/react/overview/ui-kit/react-native/getting-started
This command initializes a new React Native project named 'ChattingApp'. It is the essential first step to set up your development environment for integrating the CometChat UI Kit.
```Bash
npx @react-native-community/cli init ChattingApp
```
--------------------------------
### Install Flutter Project Packages with `flutter pub get`
Source: https://www.cometchat.com/docs/ui-kit/react/overview/notifications/flutter-push-notifications
Execute this command in your Flutter project's root directory to download and install all the dependencies listed in your `pubspec.yaml` file. This step is crucial after modifying `pubspec.yaml` to ensure all required packages are available for your application to compile and run correctly.
```Shell
flutter pub get
```
--------------------------------
### Run CometChat React Application for Local Preview
Source: https://www.cometchat.com/docs/ui-kit/react/overview/ui-kit/react/builder-integration-nextjs
Use npm start to launch the CometChat React application locally after installing dependencies and configuring credentials. This command initiates the development server, enabling you to preview the integrated chat experience in your browser.
```Shell
npm start
```
--------------------------------
### NPM: Start React Development Server
Source: https://www.cometchat.com/docs/ui-kit/react/overview/ui-kit/react/builder-integration-nextjs
This command initiates the development server for your React application. It allows you to view and test your application locally during the development phase. This is a standard practice for most React projects.
```bash
npm run dev
```
--------------------------------
### Add CometChatSDK Dependency to iOS Podfile
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/ios/setup
Insert these lines into your `Podfile` to declare the CometChatSDK as a dependency for your iOS application. This specifies the SDK version and ensures it's included during the pod installation process.
```Swift
platform :ios, '11.0'
use_frameworks!
target 'MyApp' do
pod 'CometChatSDK', '4.0.54'
end
```
--------------------------------
### Add CometChat SDK Dependency in pubspec.yaml
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/flutter/setup
This snippet shows how to add the 'cometchat_sdk' dependency to your Flutter project's 'pubspec.yaml' file. Running 'pub get' after adding this line will fetch the SDK.
```Dart
cometchat_sdk: ^4.0.19
```
--------------------------------
### Complete CometChat UI Kit Initialization Example (Java/Kotlin)
Source: https://www.cometchat.com/docs/ui-kit/react/overview/ui-kit/android/methods
This code snippet demonstrates a full implementation of the CometChatUIKit.init() method, including the construction of the UIKitSettings object. It shows how to handle both successful initialization and potential errors using a CallbackListener. This example is vital for setting up the SDK correctly.
```Java
UIKitSettings uiKitSettings = new UIKitSettings.UIKitSettingsBuilder()
.setRegion(your_region)
.setAppId(your_appID)
.setAuthKey(your_authKey)
.subscribePresenceForAllUsers().build();
CometChatUIKit.init(context, uiKitSettings, new CometChat.CallbackListener() {
@Override
public void onSuccess(String response) {
Log.i(TAG, "CometChat init onSuccess: "+response);
@Override
public void onError(CometChatException e) {
Log.e(TAG, "CometChat init exception: "+e);
}
});
```
```Kotlin
val uiKitSettings: UIKitSettings = UIKitSettingsBuilder()
.setRegion(your_region)
.setAppId(your_appID)
.setAuthKey(your_authKey)
.subscribePresenceForAllUsers()
.build()
CometChatUIKit.init(context, uiKitSettings, object : CometChat.CallbackListener() {
override fun onSuccess(response: String) {
Log.i(TAG, "CometChat init onSuccess: $response")
}
override fun onError(e: CometChatException) {
Log.e(TAG, "CometChat init exception: $e")
}
})
```
--------------------------------
### Import CometChat Object in JavaScript
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/javascript/setup-sdk
After installing the CometChat JavaScript SDK, this snippet shows how to import the `CometChat` object into your JavaScript files. This import statement makes the SDK's functionalities available for use in your application.
```JavaScript
import { CometChat } from "@cometchat/chat-sdk-javascript";
```
--------------------------------
### Initialize React Router Project with npx
Source: https://www.cometchat.com/docs/ui-kit/react/overview/ui-kit/react/react-router-integration
This command initializes a new React Router project using `npx create-react-router`. It sets up the basic project structure and navigates into the newly created directory, preparing the environment for further development of your React application.
```bash
npx create-react-router@latest my-app
cd my-app
```
--------------------------------
### Bitly Get Groups API for GUID Retrieval
Source: https://www.cometchat.com/docs/ui-kit/react/overview/fundamentals/bitly
To configure the Bitly extension, you must obtain your group's GUID using the Bitly Get Groups API. This API requires an Access Token for authentication and returns a list of groups, from which you can extract the necessary GUID.
```APIDOC
Method: GET
Endpoint: https://dev.bitly.com/api-reference#getGroups
Authentication: Bearer Token (Access Token)
Parameters: None (typically)
Response Body Example (JSON):
{
"data": {
"groups": [
{
"guid": "YOUR_GROUP_GUID_1",
"name": "Group One"
},
{
"guid": "YOUR_GROUP_GUID_2",
"name": "Group Two"
}
]
}
}
Usage: Use your generated Access Token in the Authorization header to call this endpoint and find your group's 'guid'.
```
--------------------------------
### Install React Native VoIP Push Notification Package
Source: https://www.cometchat.com/docs/ui-kit/react/overview/notifications/react-native-push-notifications
This snippet provides the installation commands for `react-native-voip-push-notification`, a crucial package for managing VoIP push notifications in React Native. After npm installation, iOS projects will also need to run `pod install` to link native dependencies. Refer to the package's documentation for further setup instructions.
```Bash
npm install react-native-voip-push-notification
# --- if using pod
cd ios/ && pod install
```
--------------------------------
### CometChat.init() Method and AppSettings API Reference
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/javascript/overview
Detailed API documentation for the `CometChat.init()` method and the `AppSettings` class, including parameters, properties, and their configurations for initializing the CometChat SDK.
```APIDOC
CometChat.init(appID: string, appSettings: AppSettings): Promise
Parameters:
- appID (string): Your CometChat App ID.
- appSettings (AppSettings): An object of the AppSettings class, created using AppSettingsBuilder.
AppSettings Class (via AppSettingsBuilder):
- setRegion(region: string): Sets the region where your app was created. (Mandatory)
- subscribePresenceForAllUsers(): Configures presence subscription for user online/offline status.
- autoEstablishSocketConnection(boolean): Manages the web-socket connection internally. Default: true.
- overrideAdminHost(adminHost: string): Overrides the default admin URL for dedicated deployments.
- overrideClientHost(clientHost: string): Overrides the default client URL for dedicated deployments.
```
--------------------------------
### Install CometChat Calls SDK Dependency for Ionic
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/ionic/calling-setup
This snippet demonstrates how to add the CometChat Calls SDK to your Ionic project using either npm or yarn. This is a crucial step to include the necessary libraries for enabling calling functionalities within your application.
```npm
npm install @cometchat/calls-sdk-ionic
```
```yarn
yarn add @cometchat/calls-sdk-ionic
```
--------------------------------
### Update iOS Minimum Target Version for CometChat Calling
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/ionic/overview
This snippet shows how to update the minimum iOS target version to 12.0 in your `Podfile`. This is a requirement for the CometChat Calling Component on iOS. After updating, run `pod install` in the `ios/App` directory to apply the changes.
```Swift
platform :ios, '12.0'
```
--------------------------------
### Run CometChat React Application Development Server
Source: https://www.cometchat.com/docs/ui-kit/react/overview/ui-kit/react/builder-integration-react-router
This section provides instructions to start the development server for the CometChat React application. It outlines the `npm run dev` command to launch the application and how to verify the chat interface by navigating to the `/chat` route in your browser. This step is essential for testing the integrated CometChat UI Kit.
```bash
npm run dev
```
--------------------------------
### Get Online Group Member Count in Swift
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/ios/retrieve-groups
This snippet demonstrates how to get the total count of online users for particular groups using the getOnlineGroupMemberCount() method. It takes an array of GUIDs and returns a dictionary mapping GUIDs to online member counts.
```Swift
let data = ["cometchat-guid-1","cometchat-guid-11"]
CometChat.getOnlineGroupMemberCount(data, onSuccess: {
countData in
print(countData)
}, onError: {
error in
print(error?.errorDescription)
})
```
```APIDOC
Method: getOnlineGroupMemberCount(data: [String], onSuccess: (Dictionary) -> Void, onError: (CometChatException?) -> Void)
Parameters:
- data: [String] - An array of group GUIDs.
Returns: Dictionary - A dictionary with the GUID as the key and the online member count for that group as the value.
```
--------------------------------
### Configure CometChat App Credentials in Dart
Source: https://www.cometchat.com/docs/ui-kit/react/overview/ui-kit/flutter/getting-started
This snippet provides an example of a dedicated Dart configuration file (`cometchat_config.dart`) to store your CometChat App ID, Region, and Auth Key. Storing credentials separately simplifies environment management and avoids hardcoding sensitive information directly in your application logic.
```Dart
class CometChatConfig {
static const String appId = "APP_ID"; // Replace with your App ID
static const String region = "REGION"; // Replace with your App Region
static const String authKey = "AUTH_KEY"; // Replace with your Auth Key
}
```
--------------------------------
### Run Next.js Development Server
Source: https://www.cometchat.com/docs/ui-kit/react/overview/ui-kit/react/next-conversation
This command initiates the Next.js development server, allowing you to preview and test your application locally. It's a standard command for starting Next.js projects and will typically open your application in a web browser at 'http://localhost:3000'.
```bash
npm run dev
```
--------------------------------
### Run Next.js Development Server
Source: https://www.cometchat.com/docs/ui-kit/react/overview/ui-kit/react/next-one-to-one-chat
This command starts the Next.js development server, allowing you to preview your application locally. It compiles your code and provides hot-reloading for a smooth development experience.
```Bash
npm run dev
```
--------------------------------
### Fetch Unread Group Messages with CometChat React
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/javascript/receive-message
This example shows how to retrieve unread messages from a specific group conversation using the CometChat SDK. It sets the group ID (GUID), enables the unread filter with `setUnread(true)`, and defines a message limit. The `fetchPrevious()` method is then invoked to get the unread messages.
```JavaScript
let GUID = "GUID";
let limit = 30;
let messagesRequest = new CometChat.MessagesRequestBuilder()
.setGUID(GUID)
.setUnread(true)
.setLimit(limit)
.build();
messagesRequest.fetchPrevious().then(
(messages) => {
console.log("Message list fetched:", messages);
},
(error) => {
console.log("Message fetching failed with error:", error);
}
);
```
```TypeScript
let GUID: string = "GUID",
limit: number = 30,
messagesRequest: CometChat.MessagesRequest =
new CometChat.MessagesRequestBuilder()
.setGUID(GUID)
.setUnread(true)
.setLimit(limit)
.build();
messagesRequest.fetchPrevious().then(
(messages: CometChat.BaseMessage[]) => {
console.log("Message list fetched:", messages);
},
(error: CometChat.CometChatException) => {
console.log("Message fetching failed with error:", error);
}
);
```
--------------------------------
### iOS: Apple Push Notification Service (APNs) Setup Guide
Source: https://www.cometchat.com/docs/ui-kit/react/overview/notifications/legacy-push-notifications
This guide details the necessary steps to configure Apple Push Notification Service (APNs) for your iOS application. It covers creating a Certificate Signing Request (CSR), generating an SSL certificate, exporting a .p12 file, and uploading APNs certificates to Firebase.
```APIDOC
### For iOS
#### Apple Developer Portal
The following steps in this section are written on the assumption that you already have an app ID assigned to your client app.
**1. Create a Certificate Signing Request**
To obtain a signing certificate required to sign apps for installation on iOS devices, you should first create a certificate signing request (CSR) file through Keychain Access on your Mac.
1. Open the Keychain Access from the utility folder, go to Keychain Access > Certificate Assistant > Request a Certificate From a Certificate Authority, and then click
2. The Certificate Information dialog box appears. Enter the email address that you use in your Apple Developer account, and enter a common name for your private key. Don't enter CA email address, choose Saved to disk, and then click the Continue button.
3. Specify the name of your CSR to save and choose the location to save the file on your local disk. Then your CSR file is created, which contains a public/private key pair.
**2. Create an SSL Certificate**
1. Sign in to your account at the [Apple Developer Member Center](https://developer.apple.com/membercenter).
2. Go to Certificates, Identifiers & Profiles. In the Identifiers > App IDs and select the Push Notifications service under Application Services.
3. Click the Edit button.
4. Under the Push Notifications service, choose which SSL certificate to create either Development or Production.
5. In the Generate your certificate pane that appears after the selection, under Upload CSR file., upload the CSR file you created through the Choose File... button. To complete the process, choose Continue. When the certificate is ready, choose Download to save it to your Mac.
6. In order to install the downloaded certificate to the KeyChain Access on your Mac, double-click it. You can find the certificate in the KeyChain Access > login > Certificates.
**3. Export and update .p12 file to Firebase**
1. Type a name for the .p12 file and save it to your Mac.
2. Browse to the location where you saved your key, select it, and click Open. Add the key ID for the key (available in Certificates, Identifiers & Profiles in the Apple Developer Member Center) and export it.
**4. Upload your APNs Certificates**
1. Go to Firebase console and open your project.
2. Inside your iOS project in the Firebase console, select settings and then select the `Cloud Messaging` tab.
3. Scroll down to iOS app configuration, click the Upload button for APNS certificate.
4. Browse to the location where you saved your APNs Certificates, select it, and click Open.
```
--------------------------------
### NPM: Start React Development Server
Source: https://www.cometchat.com/docs/ui-kit/react/overview/ui-kit/react/react-router-tab-based-chat
This command initiates the development server for a React application. Running `npm run dev` typically compiles the project, watches for file changes, and serves the application locally, enabling developers to preview their changes in real-time.
```Shell
npm run dev
```
--------------------------------
### Initialize Next.js Project with TypeScript
Source: https://www.cometchat.com/docs/ui-kit/react/overview/ui-kit/react/next-js-integration
This command initializes a new Next.js project named 'my-app' with TypeScript support using 'create-next-app'. It sets up the basic project structure and includes a subsequent command to navigate into the newly created directory, preparing it for development.
```bash
npx create-next-app@latest my-app --typescript
cd my-app
```
--------------------------------
### Integrate Bitly API: Obtain Access Token and Group GUID
Source: https://www.cometchat.com/docs/ui-kit/react/overview/extensions/bitly
This section outlines the necessary steps to obtain your Bitly Access Token and Group GUID, which are essential for configuring the Bitly extension in CometChat. It involves signing up with Bitly, generating an access token, and using the Bitly Get Groups API to fetch your group's GUID.
```APIDOC
Steps to obtain Bitly Access Token and Group GUID:
1. Sign up and log in to Bitly: https://bitly.com/
2. Navigate to Account Settings -> API.
3. Click on "Generate Token" to create a new Access Token.
4. Use the generated Access Token to call Bitly's Get Groups API to fetch your Group's GUID.
- API Endpoint: https://dev.bitly.com/api-reference#getGroups
- Authentication: Bearer Token (using the generated Access Token)
- Purpose: Retrieve the unique identifier (GUID) for your Bitly group.
- Required for CometChat extension settings.
```
--------------------------------
### Install CometChat Calls Framework with CocoaPods
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/ios/calling-integration
This command installs the CometChatCalls framework and other dependencies defined in your Podfile. Run this after adding the pods to your Podfile to integrate them into your iOS project. Specific commands are provided for different architectures.
```Swift
$ pod install
```
```Swift
$ pod install --repo-update
```
```Swift
arch -x86_64 pod install
```
--------------------------------
### Install Firebase SDK with Yarn
Source: https://www.cometchat.com/docs/ui-kit/react/overview/notifications/legacy-push-notifications
This snippet demonstrates how to install the Firebase SDK using Yarn for web applications. Yarn is an alternative package manager to npm, providing similar functionality.
```yarn
yarn add firebase
```
--------------------------------
### Start React Development Server
Source: https://www.cometchat.com/docs/ui-kit/react/overview/ui-kit/react/react-router-one-to-one-chat
Execute this command in your terminal to launch the development server for your React application. This allows you to view and test the integrated CometChat UI Kit in a web browser, typically at `http://localhost:3000/chat`.
```Shell
npm run dev
```
--------------------------------
### Install react-native-callkeep for React Native VoIP
Source: https://www.cometchat.com/docs/ui-kit/react/overview/notifications/react-native-push-notifications
This snippet demonstrates how to install the `react-native-callkeep` package, which is essential for handling VoIP call functionalities in React Native applications. Note that additional platform-specific installation steps are required after running these commands, as detailed in the package's official documentation.
```Bash
npm install react-native-callkeep
//or
yarn add react-native-callkeep
```
--------------------------------
### CometChat API Reference: init() Method and AppSettings Class
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/react-native/setup-sdk
This section provides detailed API documentation for the `CometChat.init()` method and the `AppSettings` class. It outlines the parameters for `init()`, including `appID` and `appSettings`, and describes the configurable properties of `AppSettings` such as `Region`, `Presence Subscription`, `autoEstablishSocketConnection`, `overrideAdminHost`, and `overrideClientHost`.
```APIDOC
class CometChat {
static init(appID: string, appSettings: AppSettings): Promise;
// Parameters:
// appID: string - Your CometChat App ID.
// appSettings: AppSettings - An object of the AppSettings class, configured via AppSettingsBuilder.
}
interface AppSettings {
// Properties configured via AppSettingsBuilder
region: string; // The region where your app was created.
presenceSubscription: string; // Represents the subscription type for user presence (real-time online/offline status).
autoEstablishSocketConnection: boolean; // Manages web-socket connection internally. Default: true.
// Methods
overrideAdminHost(adminHost: string): void;
// Parameters:
// adminHost: string - The admin URL to use instead of the default.
overrideClientHost(clientHost: string): void;
// Parameters:
// clientHost: string - The client URL to use instead of the default.
}
class AppSettingsBuilder {
constructor();
subscribePresenceForAllUsers(): AppSettingsBuilder;
setRegion(region: string): AppSettingsBuilder;
autoEstablishSocketConnection(value: boolean): AppSettingsBuilder;
build(): AppSettings;
}
```
--------------------------------
### Run React Application Development Server
Source: https://www.cometchat.com/docs/ui-kit/react/overview/ui-kit/react/builder-integration
This snippet provides commands to start the development server for React applications. It includes commands for projects set up with Vite/Next.js and Create React App (CRA). Choose the appropriate command based on your project's build tool.
```Shell
npm run dev
```
```Shell
npm start
```
--------------------------------
### Swift: Initiate a Call Session with CometChatCalls
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/ios/direct-calling
This Swift code demonstrates how to start a call session using `CometChatCalls.startSession`. It requires a valid `callToken`, configured `callSettings`, and a `callView` to display the UI. Error handling is included to manage potential issues during session initiation.
```Swift
guard let callToken = self.callToken, let callSettings = self.callSettings, let view = callView else { return }
CometChatCalls.startSession(callToken: callToken, callSetting: callSettings, view: view) { success in
print("CometChatCalls startSession success: \(success)")
} onError: { error in
print("CometChatCalls startSession error: \(String(describing: error?.errorDescription))")
}
```
--------------------------------
### Install CometChat Calls SDK for React Native
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/react-native/calling-setup
Install the CometChat Calls SDK using npm or yarn. This package is essential for integrating real-time calling functionalities into your React Native application.
```npm
npm install @cometchat/calls-sdk-react-native
```
```Yarn
yarn add @cometchat/calls-sdk-react-native
```
--------------------------------
### Run React Development Server with npm
Source: https://www.cometchat.com/docs/ui-kit/react/overview/ui-kit/react/react-one-to-one-chat
This command initiates the development server for a React project, compiling the application and making it accessible in a web browser. It is a standard practice for local development and testing of React applications, including those integrating CometChat UI Kit components.
```Bash
npm start
```
--------------------------------
### Initialize Podfile for iOS with CocoaPods
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/ios/calling-integration
This snippet initializes a Podfile in your iOS project directory using CocoaPods, preparing it for dependency management. Run this command in your project's root directory.
```Swift
$ pod init
```
--------------------------------
### Dart: Get Online Group Member Count
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/flutter/retrieve-groups
The 'CometChat.getOnlineGroupMemberCount()' method retrieves the count of online members for specified groups. Provide a list of group GUIDs; the method returns a Map where keys are GUIDs and values are online member counts.
```Dart
List guids = [];
guids.add("cometchat-guid-1");
guids.add("cometchat-guid-11");
CometChat.getOnlineGroupMemberCount(guids,
onSuccess: (Map count) {
debugPrint("Fetched Online Group Member Count Successfully : $count ");
}, onError: (CometChatException e) {
debugPrint("Online Group Member failed with exception: ${e.message}");
});
```
--------------------------------
### CometChat Chat and Management APIs Overview
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/ios/setup
Explore CometChat's core APIs. Chat APIs enable programmatic management of users, groups, and conversations. Management APIs facilitate app creation, webhook configuration, and dashboard feature access.
```APIDOC
Chat APIs:
Purpose: Connect CometChat with your app and programmatically manage users, groups and conversations.
Reference: https://api-explorer.cometchat.com/reference/chat-apis
Management APIs:
Purpose: Create and manage your CometChat apps, trigger webhooks and access dashboard features.
Reference: https://api-explorer.cometchat.com/reference/management-apis
```
--------------------------------
### Install Firebase SDK for React Native Messaging
Source: https://www.cometchat.com/docs/ui-kit/react/overview/notifications/legacy-push-notifications
This section provides commands to install the necessary Firebase SDK packages for integrating Firebase App and Messaging functionalities into a React Native project. Both npm and yarn commands are included for convenience.
```npm
npm install @react-native-firebase/app @react-native-firebase/messaging
```
```yarn
yarn add @react-native-firebase/app @react-native-firebase/messaging
```
--------------------------------
### Open Podfile in Xcode for Editing
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/ios/calling-integration
This command opens the Podfile in Xcode, allowing you to easily edit and manage your project's dependencies. Run this from your project's root directory after initializing the Podfile.
```Swift
open -a Xcode Podfile
```
--------------------------------
### Initialize CometChatCalls Method
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/android/setup-calling
The `init()` method is crucial for setting up CometChatCalls. It requires an Android `context` and a `CallAppSettings` object, which can be built to specify your CometChat App ID, Region, and an optional custom Host. This method should ideally be called within your activity's `onCreate()` method to ensure proper setup.
```Java
private Context context = this;
private String appID = "APP_ID"; // Replace with your App ID
private String region = "REGION"; // Replace with your App Region ("eu" or "us")
CallAppSettings callAppSettings = CallAppSettingBuilder()
.setAppId(appID)
.setRegion(region)
.build();
CometChatCalls.init(
context,
callAppSettings,
new CometChatCalls.CallbackListener() {
override public void onSuccess(String successMessage) {
}
override public void onError(CometChatException e) {
}
}
)
```
```Kotlin
val context:Context = this // Replace with your App Region ("eu" or "us")
val appID:String ="APP_ID" // Replace with your App ID
val region:String ="REGION" // Replace with your App Region ("eu" or "us")
val callAppSettings = CallAppSettingBuilder()
.setAppId(appID)
.setRegion(region).build()
CometChatCalls.init(
context,
callAppSettings,
object : CometChatCalls.CallbackListener() {
override fun onSuccess(s: String?) {
}
override fun onError(e: CometChatException) {
}
}
)
```
```APIDOC
{
"class": "CometChatCalls",
"method": {
"name": "init",
"description": "Initializes the settings required for CometChatCalls.",
"parameters": [
{
"name": "context",
"type": "Context",
"description": "Your activity context or Android context for your application."
},
{
"name": "callAppSettings",
"type": "CallAppSettings",
"description": "An object of the CallAppSettings class, created using CallAppSettingBuilder. This object configures App ID, Region, and an optional Host.",
"details": {
"class_name": "CallAppSettings",
"builder_class": "CallAppSettingBuilder",
"properties": [
{"name": "appId", "type": "String", "description": "CometChat app ID (mandatory). Set using setAppId()."},
{"name": "region", "type": "String", "description": "The region where your app was created (mandatory). Set using setRegion()."},
{"name": "host", "type": "String", "description": "Client URL to use instead of the default, for dedicated deployments. Set using setHost()."}
]
}
},
{
"name": "callbackListener",
"type": "CometChatCalls.CallbackListener",
"description": "A listener to handle success or error callbacks.",
"callbacks": [
{"name": "onSuccess", "parameters": [{"name": "successMessage", "type": "String"}], "description": "Called upon successful initialization."},
{"name": "onError", "parameters": [{"name": "e", "type": "CometChatException"}], "description": "Called if an error occurs during initialization."}
]
}
],
"return_type": "void",
"usage_note": "Suggested to call on activity onCreate() method."
}
}
```
--------------------------------
### Retrieve Specific CometChat Group Details by GUID in React
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/react-native/retrieve-groups
To get information for a specific group, use the CometChat.getGroup() method. It requires the Group ID (GUID) as a parameter. This method returns a Group object containing the details of the requested group.
```JavaScript
var GUID = "GUID";
CometChat.getGroup(GUID).then(
(group) => {
console.log("Group details fetched successfully:", group);
},
(error) => {
console.log("Group details fetching failed with exception:", error);
}
);
```
```TypeScript
var GUID: string = "GUID";
CometChat.getGroup(GUID).then(
(group: CometChat.Group) => {
console.log("Group details fetched successfully:", group);
},
(error: CometChat.CometChatException) => {
console.log("Group details fetching failed with exception:", error);
}
);
```
```APIDOC
Method: CometChat.getGroup(GUID: string)
Description: Retrieves details for a specific group.
Parameters:
- GUID: string - The GUID of the group for whom the details are to be fetched.
Returns: CometChat.Group - An object containing the details of the group.
```
--------------------------------
### Comprehensive CometChat CardMessage Example in Typescript
Source: https://www.cometchat.com/docs/ui-kit/react/overview/web-shared/card-message
Provides a complete example of creating and manipulating a `CardMessage` instance, including `APIAction` and `ButtonElement` setup, and setting an image URL. This snippet covers common usage patterns and demonstrates the full lifecycle of a card message.
```Typescript
// Create an instance of APIAction
let apiAction = new APIAction("https://example.com/api", "POST");
// Create instance of ButtonElement for card actions
let cardAction = new ButtonElement("1", apiAction, "Click Me");
// Create a new instance of CardMessage
let cardMessage = new CardMessage("receiverId", CometChat.RECEIVER_TYPE.USER, "customType", "This is a card", [cardAction]);
cardMessage.setImageUrl("https://example.com/image.png");
```
--------------------------------
### Initialize and Log In CometChat UI Kit for Android
Source: https://www.cometchat.com/docs/ui-kit/react/overview/ui-kit/android/getting-started
This code snippet demonstrates how to initialize the CometChat UI Kit with your application credentials and then log in a user. It includes error handling for both initialization and login processes, and provides options for launching different chat experiences after successful login.
```Java
.setRegion(region)
.setAppId(appID)
.setAuthKey(authKey)
.subscribePresenceForAllUsers()
.build();
CometChatUIKit.init(this, uiKitSettings, new CometChat.CallbackListener() {
@Override
public void onSuccess(String success) {
Log.d(TAG, "Initialization completed successfully");
loginUser();
}
@Override
public void onError(CometChatException e) {
Log.e(TAG, "Initialization failed: " + (e != null ? e.getMessage() : "Unknown error"));
}
});
}
private void loginUser() {
CometChatUIKit.login("cometchat-uid-1", new CometChat.CallbackListener() {
@Override
public void onSuccess(User user) {
Log.d(TAG, "Login successful for user: " + user.getUid());
// ✅ Option 1: Launch One-to-One or Group Chat Screen
// Intent intent = new Intent(MainActivity.this, MessageActivity.class);
// intent.putExtra("uid", "cometchat-uid-1");
// startActivity(intent);
// ✅ Option 2: Launch Conversation List + Message View
// startActivity(new Intent(MainActivity.this, ConversationActivity.class));
// ✅ Option 3: Launch Tab-Based Chat Experience (Chats, Calls, Users, Groups)
// startActivity(new Intent(MainActivity.this, TabbedActivity.class));
}
@Override
public void onError(CometChatException e) {
Log.e("Login", "Login failed: " + (e != null ? e.getMessage() : "Unknown error"));
}
});
}
```
--------------------------------
### Install React Native Firebase Packages for Push Notifications
Source: https://www.cometchat.com/docs/ui-kit/react/overview/sdk/react-native/push-notification-setup
This snippet provides commands for installing the @react-native-firebase/app and @react-native-firebase/messaging packages using both NPM and Yarn. These packages are fundamental for enabling Firebase services and push notification capabilities in your React Native project.
```Javascript
npm install @react-native-firebase/app @react-native-firebase/messaging
```
```Javascript
yarn add @react-native-firebase/app @react-native-firebase/messaging
```
--------------------------------
### Comprehensive TextInputElement Usage Example in Typescript
Source: https://www.cometchat.com/docs/ui-kit/react/overview/ui-kit/angular/interactive-text-input-element
This example provides a complete demonstration of creating and configuring a TextInputElement instance. It shows importing the class, setting maximum lines, defining placeholder text, and assigning a default value, illustrating typical setup steps.
```Typescript
// Import the class
import { TextInputElement } from "./TextInputElement";
// Create a new instance of the class
let inputElement = new TextInputElement("1", "Name");
// Set the max lines
inputElement.setMaxLines(1);
// Set the placeholder text
inputElement.setPlaceholder("Enter your name");
// Set the default value
inputElement.setDefaultValue("John Doe");
```
--------------------------------
### Initialize CometChat UI Kit with SDK Settings
Source: https://www.cometchat.com/docs/ui-kit/react/overview/ui-kit/vue/ui-kit-methods
This method initializes the CometChat SDK with required settings for the UI Kit. It uses `UIKitSettingsBuilder` to configure APP_ID, REGION, and an optional AUTH_KEY. Call `init()` on app startup to prepare the SDK for user login.
```Javascript
import { UIKitSettingsBuilder } from "@cometchat/uikit-shared";
const COMETCHAT_CONSTANTS = {
APP_ID: "APP_ID", // Replace with your App ID
REGION: "REGION", // Replace with your App Region
AUTH_KEY: "AUTH_KEY", // Replace with your Auth Key
};
//create the builder
const UIKitSettings = new UIKitSettingsBuilder()
.setAppId(COMETCHAT_CONSTANTS.APP_ID)
.setRegion(COMETCHAT_CONSTANTS.REGION)
.setAuthKey(COMETCHAT_CONSTANTS.AUTH_KEY)
.subscribePresenceForAllUsers()
.setExtensions() //pass an array of extensions to enable. By default all the extensions will be enabled
.build();
//Initialize CometChat
CometChatUIKit.init(UIKitSettings)?.then(() => {
//login your user
});
```