Authenticate and manage a session
Initialize the OpenIM React Native SDK, sign in, check login status, handle connection callbacks, and log out the current account.
Before configuring authentication and managing sessions, complete the setup described in Before you start and Environment-specific implementation. Initialize the OpenIM React Native SDK using initSDK(), then authenticate the current user and establish the WebSocket connection with login().
The complete integration workflow is:
- Invoke
initSDK()to configure service endpoints, local storage, and logging parameters. - Register event listeners for
onConnecting,onConnectSuccess, andonConnectFailed. - Invoke
login()with user credentials to authenticate. - Await the
onConnectSuccessevent to verify that the long-lived connection is ready. - Invoke
logout()when actively signing out or switching accounts.
Initialize the SDK
Call initSDK() with the server addresses, application-writable data directory, and logging options. Both dataDir and logFilePath must point to persistent directories that the application has permission to write to.
React Native CLI
import OpenIMSDK, { LogLevel } from '@openim/rn-client-sdk';
import RNFS from 'react-native-fs';
const dataDir = RNFS.DocumentDirectoryPath;
await OpenIMSDK.initSDK({
apiAddr: 'http://your-server-ip:10002',
wsAddr: 'ws://your-server-ip:10001',
dataDir,
logFilePath: dataDir,
logLevel: LogLevel.Info,
isLogStandardOutput: true,
});Expo
Expo projects retrieve the application document directory using expo-file-system. The URI returned by documentDirectory contains a file:// scheme prefix that must be stripped before passing the path to the SDK:
import OpenIMSDK, { LogLevel } from '@openim/rn-client-sdk';
import * as FileSystem from "expo-file-system/legacy";
const dataDir = FileSystem.documentDirectory.replace(/^file:\/\//, '').replace(/\/$/, '');
await OpenIMSDK.initSDK({
apiAddr: 'http://your-server-ip:10002',
wsAddr: 'ws://your-server-ip:10001',
dataDir,
logFilePath: dataDir,
logLevel: LogLevel.Info,
isLogStandardOutput: true,
});Parameters
Core configuration parameters accepted by initSDK():
| Parameter | Type | Required | Description |
|---|---|---|---|
apiAddr | string | Yes | OpenIMServer HTTP API address. |
wsAddr | string | Yes | OpenIMServer WebSocket address. |
dataDir | string | Yes | SDK local SQLite database directory, located within the application writable sandbox. |
logFilePath | string | Yes | SDK local log directory, located within the application writable sandbox. |
logLevel | LogLevel | No | Log verbosity level configured via the LogLevel enum (e.g. LogLevel.Info). |
isLogStandardOutput | boolean | No | Whether to print underlying SDK logs to the platform standard console. |
Register connection events
Register connection listeners before calling login(). Event names can use string literals matching the callback names:
const handleConnecting = () => {
console.log("onConnecting");
};
const handleConnectSuccess = () => {
console.log("onConnectSuccess");
};
const handleConnectFailed = (error: OpenIMEventBaseErrorType) => {
console.log("onConnectFailed", error.errCode, error.errMsg);
};
// Register listeners
OpenIMSDK.on('onConnecting', handleConnecting);
OpenIMSDK.on('onConnectSuccess', handleConnectSuccess);
OpenIMSDK.on('onConnectFailed', handleConnectFailed);Sign in the current user
Pass the userID and session token provided by your application backend to login():
await OpenIMSDK.login({
userID,
token,
});Return value
When the Promise resolves, the sign-in request has been accepted. Wait for the onConnectSuccess event before invoking business data operations (such as loading conversations or messages).
Check login status
Query the current session state using getLoginStatus():
const loginStatus = await OpenIMSDK.getLoginStatus();The returned LoginStatus indicates one of the following states:
| State | Description |
|---|---|
LoginStatus.Logout | The SDK instance is not authenticated. |
LoginStatus.Logging | The sign-in and connection workflow is in progress. |
LoginStatus.Logged | The SDK instance is fully authenticated and connected. |
Log out and switch accounts
Invoke logout() when the user signs out or switches accounts, and clear all local application-level cache for the current session:
await OpenIMSDK.logout();When switching accounts, wait for logout() to complete before calling login() with the new account's credentials. There is no need to re-invoke initSDK(). Never sign into a second account while the current session remains active.
Remove event listeners
When logging out, switching accounts, or unmounting associated screens, call off() with the exact event name and function reference used during registration:
// Unregister listeners
OpenIMSDK.off('onConnecting', handleConnecting);
OpenIMSDK.off('onConnectSuccess', handleConnectSuccess);
OpenIMSDK.off('onConnectFailed', handleConnectFailed);Next steps
Was this page helpful?