### Install Node.js Project Dependencies via npm Source: https://doc.easemob.com/document/web/quickstart This shell command uses npm to install all project dependencies declared in the `package.json` file, preparing the environment for development or production builds. ```shell $ npm install ``` -------------------------------- ### Project Dependencies and Scripts Configuration (package.json) Source: https://doc.easemob.com/document/web/quickstart This `package.json` defines the project's metadata, lists essential dependencies including 'easemob-websdk', 'webpack', and 'webpack-dev-server', and specifies npm scripts for building and starting the development server. ```json { "name": "web", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "build": "webpack --config webpack.config.js", "start:dev": "webpack serve --open --config webpack.config.js" }, "dependencies": { "easemob-websdk": "latest", "webpack": "^5.50.0", "webpack-dev-server": "^3.11.2", "webpack-cli": "^4.8.0" }, "author": "", "license": "ISC" } ``` -------------------------------- ### Yarn Commands for React Native Project Management Source: https://doc.easemob.com/document/react-native/quickstart These shell commands provide quick ways to compile and run the React Native application on different platforms (iOS, Android) and to start the development server for debugging and live reloading. ```shell yarn run ios ``` ```shell yarn run android ``` ```shell yarn run start ``` -------------------------------- ### Easemob Server-Side Token Acquisition APIs Source: https://doc.easemob.com/document/react-native/quickstart This documentation highlights the necessity of integrating server-side APIs for secure token acquisition in production environments. Specifically, it refers to the 'Get App Token API' and 'Get User Token API' which should be called from the application server to provide tokens to clients. ```APIDOC API Category: Token Acquisition Description: APIs for securely obtaining authentication tokens from a server-side environment. APIs: - Name: Get App Token API Endpoint: /document/server-side/easemob_app_token.html Purpose: To obtain an application-level token for server-side operations. - Name: Get User Token API Endpoint: /document/server-side/easemob_user_token.html Purpose: To obtain a user-specific token for client authentication. Usage Note: These APIs should be integrated into your application server to provide tokens to client applications for enhanced security in production environments. ``` -------------------------------- ### cURL Example for Querying Easemob Callback Storage Info Source: https://doc.easemob.com/document/server-side/callback_postsending A cURL command example demonstrating how to make a GET request to query the Easemob callback storage information, including the Authorization header. ```curl curl -X GET 'https://a1.easemob.com/easemob-demo/easeim/callbacks/storage/info' \ -H 'Authorization: Bearer ' ``` -------------------------------- ### Example API Response for User List Source: https://doc.easemob.com/document/server-side/account_system An example JSON response showing the structure for retrieving a list of users, including user details and pagination cursor. ```json { "action": "get", "path": "/users", "uri": "https://XXXX/XXXX/XXXX/users/XXXX", "entities": [ { "uuid": "0ffe2d80-XXXX-XXXX-8d66-279e3e1c214b", "type": "user", "created": 1542795196504, "modified": 1542795196504, "username": "XXXX", "activated": true, "nickname": "testuser" } ], "timestamp": 1542798985011, "duration": 6, "count": 1 } ``` -------------------------------- ### cURL Example: Get First Page of Users Source: https://doc.easemob.com/document/server-side/account_system cURL command to retrieve the first 2 users, demonstrating the initial API call without a cursor. ```bash curl -X GET -H 'Accept: application/json' -H 'Authorization: Bearer ' 'https://XXXX/XXXX/XXXX/users?limit=2' ``` -------------------------------- ### Example API Response for Paginated User List Source: https://doc.easemob.com/document/server-side/account_system An example JSON response showing a paginated list of users, including user details and a cursor for subsequent requests. ```json { "action": "get", "path": "/users", "uri": "https://XXXX/XXXX/XXXX/users", "entities": [ { "uuid": "ab90eff0-XXXX-XXXX-9174-8f161649a182", "type": "user", "created": 1542356511855, "modified": 1542356511855, "username": "XXXX", "activated": true, "nickname": "user1" }, { "uuid": "b2aade90-XXXX-XXXX-a974-f3368f82e4f1", "type": "user", "created": 1542356523769, "modified": 1542356523769, "username": "user2", "activated": true, "nickname": "user2" } ], "timestamp": 1542558467056, "duration": 11, "cursor": "LTgzXXXX2tB", "count": 2 } ``` -------------------------------- ### Build Project with Webpack via npm Script Source: https://doc.easemob.com/document/web/quickstart This shell command executes the 'build' script defined in `package.json`, triggering Webpack to compile and bundle the project's source code into deployable assets. ```shell # Use webpack to package. $ npm run build ``` -------------------------------- ### Webpack Configuration for Bundling and Development Server Source: https://doc.easemob.com/document/web/quickstart This `webpack.config.js` file configures Webpack for the project. It sets the entry point, output path for the bundled JavaScript, and defines development server settings such as compression, port, and HTTPS. ```javascript const path = require('path'); module.exports = { entry: './index.js', mode: 'production', output: { filename: 'bundle.js', path: path.resolve(__dirname, './dist'), }, devServer: { compress: true, port: 9000, https: true } }; ``` -------------------------------- ### Example Response for Chatroom Whitelist User List Source: https://doc.easemob.com/document/server-side/chatroom_member_allowlist An example JSON response showing the list of users currently in a chatroom's whitelist. This is typically a response from a GET request to retrieve whitelist members. ```json { "action": "get", "application": "5cXXXX75d", "uri": "https://XXXX/XXXX/XXXX/chatrooms/66XXXX33/white/users", "entities": [], "data": ["wzy_test", "wzy_vivo", "wzy_huawei", "wzy_xiaomi", "wzy_meizu"], "timestamp": 1594724947117, "duration": 3, "organization": "XXXX", "applicationName": "testapp", "count": 5 } ``` -------------------------------- ### Easemob Web SDK Initialization and Event Handling Source: https://doc.easemob.com/document/web/quickstart This JavaScript code demonstrates the integration of Easemob Web SDK. It initializes the connection, registers event handlers for connection status and incoming messages, and implements user authentication (register, login, logout) and single chat message sending functionalities. ```javascript import WebIM from 'easemob-websdk' const appKey = "" let username, password // Initialize client. For related parameter configuration, see the `Connection` class in the API reference. WebIM.conn = new WebIM.connection({ // Note that "K" here must be capitalized. appKey: appKey, }) // Add callback functions. WebIM.conn.addEventHandler('connection&message', { onConnected: () => { document.getElementById("log").appendChild(document.createElement('div')).append("Connect success !") }, onDisconnected: () => { document.getElementById("log").appendChild(document.createElement('div')).append("Logout success !") }, onTextMessage: (message) => { console.log(message) document.getElementById("log").appendChild(document.createElement('div')).append("Message from: " + message.from + " Message: " + message.msg) }, onError: (error) => { console.log('on error', error) } }) // Button behavior definition. window.onload = function () { // Register. document.getElementById("register").onclick = function(){ username = document.getElementById("userID").value.toString() password = document.getElementById("password").value.toString() WebIM.conn .registerUser({ username, password }) .then((res) => { document .getElementById("log") .appendChild(document.createElement("div")) .append(`register user ${username} success`); }) .catch((e) => { document .getElementById("log") .appendChild(document.createElement("div")) .append(`${username} already exists`); }); } // Login. document.getElementById("login").onclick = function () { username = document.getElementById("userID").value.toString() password = document.getElementById("password").value.toString() WebIM.conn .open({ user: username, pwd: password }) .then((res) => { document .getElementById("log") .appendChild(document.createElement("div")) .append(`Login Success`); }) .catch((e) => { document .getElementById("log") .appendChild(document.createElement("div")) .append(`Login failed`); }); } // Logout. document.getElementById("logout").onclick = function () { WebIM.conn.close(); } // Send a single chat message. document.getElementById("send_peer_message").onclick = function () { let peerId = document.getElementById("peerId").value.toString() let peerMessage = document.getElementById("peerMessage").value.toString() let option = { chatType: 'singleChat', // Conversation type, set to single chat. type: 'txt', // Message type. to: peerId, // Message recipient (User ID). msg: peerMessage // Message content. } let msg = WebIM.message.create(option); WebIM.conn.send(msg).then((res) => { console.log('send private text success'); document.getElementById("log").appendChild(document.createElement('div')).append("Message send to: " + peerId + " Message: " + peerMessage) }).catch(() => { console.log('send private text fail'); }) } } ``` -------------------------------- ### Install Easemob Web SDK via npm or yarn Source: https://doc.easemob.com/document/web/import_sdk_minicore Before using the SDK, it needs to be installed using a package manager like npm or yarn. ```Shell npm install easemob-websdk ``` ```Shell yarn add easemob-websdk ``` -------------------------------- ### TypeScript Import for Easemob Web SDK Types Source: https://doc.easemob.com/document/web/quickstart This snippet illustrates the correct way to import the Easemob Web SDK along with its type definitions in a TypeScript project, facilitating type-safe development. ```typescript import WebIM, { EasemobChat } from 'easemob-websdk' ``` -------------------------------- ### Get App Chat Groups Request Example (First Page) Source: https://doc.easemob.com/document/server-side/group_manage Example `curl` command to retrieve the first page of chat groups from an application, specifying a limit of 2 groups. Requires an App Token for authorization. ```bash # Replace with your server-generated App Token curl -X GET -H 'Accept: application/json' -H 'Authorization: Bearer ' 'https://XXXX/XXXX/XXXX/chatgroups?limit=2' ``` -------------------------------- ### React Native Application Stylesheet Source: https://doc.easemob.com/document/react-native/quickstart This JavaScript snippet defines the visual styles for the React Native chat application's UI elements, including containers, text inputs, buttons, and log display areas, using `StyleSheet.create`. ```javascript const styles = StyleSheet.create({ titleContainer: { height: 60, backgroundColor: '#6200ED', }, title: { lineHeight: 60, paddingLeft: 15, color: '#fff', fontSize: 20, fontWeight: '700', }, inputCon: { marginLeft: '5%', width: '90%', height: 60, paddingBottom: 6, borderBottomWidth: 1, borderBottomColor: '#ccc', }, inputBox: { marginTop: 15, width: '100%', fontSize: 14, fontWeight: 'bold', }, buttonCon: { marginLeft: '2%', width: '96%', flexDirection: 'row', marginTop: 20, height: 26, justifyContent: 'space-around', alignItems: 'center', }, eachBtn: { height: 40, width: '28%', lineHeight: 40, textAlign: 'center', color: '#fff', fontSize: 16, backgroundColor: '#6200ED', borderRadius: 5, }, btn2: { height: 40, width: '45%', lineHeight: 40, textAlign: 'center', color: '#fff', fontSize: 16, backgroundColor: '#6200ED', borderRadius: 5, }, logText: { padding: 10, marginTop: 10, color: '#ccc', fontSize: 14, lineHeight: 20, } }); ``` -------------------------------- ### Get App Chat Groups Request Example (Second Page with Cursor) Source: https://doc.easemob.com/document/server-side/group_manage Example `curl` command to retrieve the second page of chat groups, using a `cursor` obtained from a previous request to continue pagination. Requires an App Token for authorization. ```bash # Replace with your server-generated App Token curl -X GET -H 'Accept: application/json' -H 'Authorization: Bearer ' 'https://XXXX/XXXX/XXXX/chatgroups?limit=2&cursor=ZGNXXXX6Mg' ``` -------------------------------- ### Generic API Response Example (Delete Action) Source: https://doc.easemob.com/document/server-side/account_system An example of a successful API response body, showing common fields like URI, timestamp, organization, application, and data for a delete operation. This demonstrates the general structure of a successful API call response. ```JSON { "uri": "https://XXX/XXX/XXX", "timestamp": 1709865422596, "organization": "XXX", "application": "6b58d05d-XXX-1ff3e95a3dc0", "entities": [], "action": "delete", "data": { "result": true }, "duration": 0, "applicationName": "90" } ``` -------------------------------- ### Send a Text Message via Easemob SDK Source: https://doc.easemob.com/document/unity/quickstart Illustrates how to create and send a text message using the Easemob SDK in C#. The example shows message creation with recipient ID and content, followed by sending the message with success and error callbacks. ```C# Message msg = Message.CreateTextSendMessage(SignChatId.text, MessageContent.text); SDKClient.Instance.ChatManager.SendMessage(ref msg, new CallBack( onSuccess: () => { AddLogToLogText($"send message succeed, receiver: {SignChatId.text}, message: {MessageContent.text}"); }, onError:(code, desc) => { AddLogToLogText($"send message failed, code: {code}, desc: {desc}"); } )); ``` -------------------------------- ### Integrate EaseMob Flutter SDK via flutter pub Source: https://doc.easemob.com/document/flutter/integration This command-line snippet demonstrates how to add the `im_flutter_sdk` dependency to a Flutter project and fetch its packages using `flutter pub add` and `flutter pub get` commands. ```Shell cd quick_start flutter pub add im_flutter_sdk flutter pub get ``` -------------------------------- ### Logout from Easemob IM System Source: https://doc.easemob.com/document/unity/quickstart Provides a C# example for logging out a user from the Easemob Instant Messaging system. It includes success and error callbacks to confirm the logout operation. ```C# SDKClient.Instance.Logout(true, callback: new CallBack( onSuccess: () => { AddLogToLogText("sign out sdk succeed"); }, onError: (code, desc) => { AddLogToLogText($"sign out sdk failed, code: {code}, desc: {desc}"); } )); ``` -------------------------------- ### React Native Chat Application UI and Interaction Logic Source: https://doc.easemob.com/document/react-native/quickstart This JavaScript code defines a React Native functional component that manages user input states, handles user authentication (login/logout), and message sending functionalities. It renders the main chat interface with input fields and interactive buttons, logging operation outcomes. ```javascript rollLog('send fail: ' + JSON.stringify(reason)); }); }; // Renders the UI. return ( {title} setUsername(text)} value={username} autoCapitalize={'none'} /> setChatToken(text)} value={chatToken} autoCapitalize={'none'} /> SIGN IN SIGN OUT setTargetId(text)} value={targetId} autoCapitalize={'none'} /> setContent(text)} value={content} autoCapitalize={'none'} /> SEND TEXT {logText} {} {} ); }; ``` -------------------------------- ### Log In User to Easemob Account with Token Source: https://doc.easemob.com/document/android/quickstart This example demonstrates how to log a user into the Easemob SDK using their user ID and token. It utilizes `EMClient.getInstance().loginWithToken()` and provides an `EMCallBack` to handle both successful login (`onSuccess`) and failed login (`onError`) scenarios. UI updates related to login status should be handled on the main thread as callbacks occur on an asynchronous thread. ```Java // 导包 import com.hyphenate.EMCallBack; import com.hyphenate.chat.EMClient; EMClient.getInstance().loginWithToken(mAccount, mPassword, new EMCallBack() { // 登录成功回调 @Override public void onSuccess() { // 回调位于异步线程,处理 UI 相关需切换到主线程 } // 登录失败回调,包含错误信息 @Override public void onError(final int code, final String error) { // 回调位于异步线程,处理 UI 相关需切换到主线程 } }); ``` -------------------------------- ### Initialize Easemob Android SDK in Main Process Source: https://doc.easemob.com/document/android/quickstart This code snippet illustrates the essential steps for initializing the Easemob Android SDK. It involves importing necessary classes, creating an `EMOptions` object to configure the AppKey and other settings, and then calling `EMClient.getInstance().init()` with the application context and options. This initialization should occur in the main process, typically within an `Application` or `Activity`. ```Java // 导包 import com.hyphenate.chat.EMClient; import com.hyphenate.chat.EMOptions; EMOptions options = new EMOptions(); options.setAppKey("Your appkey"); ......// 其他 EMOptions 配置。 // context 为上下文,在 Application 或者 Activity 中可以用 this 代替 EMClient.getInstance().init(context, options); ``` -------------------------------- ### cURL Example: Get Single User Online Status Source: https://doc.easemob.com/document/server-side/account_system A cURL command example demonstrating how to make a GET request to retrieve a single user's online status, including required `Accept` and `Authorization` headers and a placeholder for the App Token. ```cURL 将 替换为你在服务端生成的 App Token curl -X GET -H 'Accept: application/json' -H 'Authorization: Bearer ' 'https://XXXX/XXXX/XXXX/users/user1/status' ``` -------------------------------- ### EC.connection Initialization Parameters API Reference Source: https://doc.easemob.com/document/applet/initialization This section provides a detailed API reference for the parameters accepted by the `EC.connection` constructor. It lists each parameter's type, whether it is required, and a comprehensive description of its purpose, default values, and any specific usage notes. ```APIDOC EC.connection(options: object) options: appKey: String (Required) Description: The unique identifier for your application generated by the Easemob IM Cloud console, composed of Appname and Orgname. isHttpDNS: Bool (Optional, Default: true) Description: Whether to enable DNS to prevent DNS hijacking. - true: enable; - false: disable. delivery: Bool (Optional, Default: false) Description: Whether to enable delivery receipts. - true: enable; - false: disable. enableReportLogs: Bool (Optional, Default: false) Description: Whether the mini-program platform allows uploading logs. - true: enable; - false: disable. https: Bool (Optional, Default: true) Description: Whether to support accessing IM via HTTPS. - true: supports HTTPS and HTTP; - false: browser decides based on domain. heartBeatWait: Int (Optional, Default: 30000) Description: Heartbeat interval in milliseconds. deviceId: String (Optional) Description: Device ID, a default random value. useOwnUploadFun: Bool (Optional, Default: false) Description: Whether to support uploading images/files to your own server via your own path. - true: supported, path needs to be specified; - false: disabled, files uploaded/downloaded via message server. autoReconnectNumMax: Int (Optional) Description: Maximum reconnection attempts. apiUrl: String (Required) Description: The specified REST server. Used when DNS is not enabled, typically for scenarios requiring data isolation and security. To get this address, check the "Rest Api" setting in the "Domain Configuration" table under "Instant Messaging > Service Overview" in the Easemob console. url: String (Required) Description: The specified message server. Used when DNS is not enabled, typically for scenarios requiring data isolation and security. To get this address, check the "WeChat Mini Program" or "Alipay Mini Program" setting in the "Domain Configuration" table under "Instant Messaging > Service Overview" in the Easemob console. ``` -------------------------------- ### Initialize AgoraChat SDK in Unity C# Source: https://doc.easemob.com/document/unity/quickstart Initializes the AgoraChat SDK using an `Options` object. You must replace the placeholder 'appkey' with your actual App Key obtained from the AgoraChat console. This initialization step is fundamental and must be completed before the SDK can perform any operations, such as sending or receiving messages. ```C# var options = new Options("appkey"); //将该参数设置为你的 App Key SDKClient.Instance.InitWithOptions(options); ``` -------------------------------- ### cURL Example: Get All User Friends (One-time) Source: https://doc.easemob.com/document/server-side/user_relationship A cURL command example for retrieving all friends of a specific user in a single request. This demonstrates the GET method and required headers for authentication and content type. ```curl # 将 替换为你在服务端生成的 App Token curl -X GET 'https://XXXX/XXXX/XXXX/users/user1/contacts/users' \ -H 'Accept: application/json' \ -H 'Authorization: Bearer ' ``` -------------------------------- ### Initialize Easemob SDK Connection Source: https://doc.easemob.com/document/applet/initialization This code snippet demonstrates how to initialize a new Easemob SDK connection using the `EC.connection` constructor. It shows the basic setup with `appKey`, `url`, and `apiUrl` parameters, which are essential for establishing communication with the Easemob services. ```JavaScript const conn = new EC.connection({ appKey: "your appKey", url: "wss://im-api-wechat.easemob.com/websocket", apiUrl: "https://a1.easemob.com", }); ``` -------------------------------- ### Get Group Announcement Request Example with cURL Source: https://doc.easemob.com/document/server-side/group_file Provides a cURL command example to demonstrate how to make an HTTP GET request to retrieve a group's announcement using the Easemob IM RESTful API. It shows the correct headers and URL format. ```curl # 将 替换为你在服务端生成的 App Token curl -X GET -H 'Content-Type: application/json' -H 'Accept: application/json' -H 'Authorization: Bearer ' 'https://XXXX/XXXX/XXXX/chatgroups/6XXXX7/announcement' ``` -------------------------------- ### Get User Notification Language Example Response Source: https://doc.easemob.com/document/server-side/push Example JSON response showing the retrieved preferred language for a user's push notifications. Note: This example response is identical to the PUT response example. ```json { "path": "/users", "uri": "https://XXXX/XXXX/XXXX/users/XXXX/notification/language", "timestamp": 1648089630244, "organization": "hx", "application": "17fe201b-XXXX-XXXX-XXXX-1ed1ebd7b227", "action": "put", "data": { "language": "EU" }, "duration": 66, "applicationName": "hxdemo" } ``` -------------------------------- ### Retrieve Conversation Messages from Local Storage (Java) Source: https://doc.easemob.com/document/harmonyos/message_retrieve This example shows how to retrieve all messages for a specific conversation from memory using `getAllMessages` and how to load additional messages from the local database in a paginated manner using `loadMoreFromDB`. The `loadMoreFromDB` method allows specifying a starting message ID and page size. ```Java EMConversation conversation = EMClient.getInstance().chatManager().getConversation(username); List messages = conversation.getAllMessages(); // startMsgId:查询的起始消息 ID。SDK 从该消息 ID 开始按消息时间戳的逆序加载。如果传入消息的 ID 为空,SDK 从最新消息开始按消息时间戳的逆序获取。 // pageSize:每页期望加载的消息数。取值范围为 [1,400]。 List messages = conversation.loadMoreFromDB(startMsgId, pagesize); ``` -------------------------------- ### cURL Request Example: Get User's Chatgroups Source: https://doc.easemob.com/document/server-side/group_manage A cURL command example demonstrating how to make an HTTP GET request to retrieve a user's joined chat groups. This snippet shows the correct syntax for including the Authorization header with an App Token. ```bash # 将 替换为你在服务端生成的 App Token curl -L -X GET 'http://XXXX/XXXX/XXXX/chatgroups/user/XXXX' \ -H 'Authorization: Bearer ' ``` -------------------------------- ### Login to Easemob IM System Source: https://doc.easemob.com/document/unity/quickstart Demonstrates how to log in a user to the Easemob Instant Messaging system using both the `Login` and the recommended `LoginWithToken` methods. It includes success and error callbacks for handling the login result. ```C# SDKClient.Instance.Login(username: Username.text, pwdOrToken: Password.text, callback: new CallBack( onSuccess: () => { AddLogToLogText("sign in sdk succeed"); }, onError:(code, desc) => { AddLogToLogText($"sign in sdk failed, code: {code}, desc: {desc}"); } )); // 说明:自 1.3.0 版本之后,建议使用 LoginWithToken 替代 Login。Password.text 中的内容需要由输入密码改为输入token SDKClient.Instance.LoginWithToken(username: Username.text, pwdOrToken: Password.text, callback: new CallBack( onSuccess: () { AddLogToLogText("sign in sdk succeed"); }, onError: (code, desc) { AddLogToLogText($"sign in sdk failed, code: {code}, desc: {desc}"); } )); ``` -------------------------------- ### JSON Response Example: Get User's Chatgroups Source: https://doc.easemob.com/document/server-side/group_manage An example JSON response for the 'Get User's Chatgroups' API call, showing the structure of the returned data including group details and pagination information. This illustrates a successful response with a list of group entities. ```json { "action": "get", "applicationName": "XXXX", "duration": 0, "entities": [ { "name": "群组名称", "avatar": "https://www.XXXX.com/XXX/image", "owner": "群组管理员", "id": "2XXXX1", "groupId": "2XXXX1", "description": "群组描述", "disabled": false, "public": false, "allowinvites": false, "membersonly": true, "maxusers": 2000, "created": 1692687427254 } ], "organization": "XXXX", "timestamp": 1692687427254, "total": 10, "uri": "http://XXXX/XXXX/XXXX/chatgroups/user/XXXX" } ``` -------------------------------- ### Real-time Chat Room Member Count Update (C#) Source: https://doc.easemob.com/document/windows/room_manage This C# example demonstrates how to dynamically update the chat room member count. Upon receiving `OnMemberJoinedFromRoom` event, it retrieves the chat room details using `SDKClient.Instance.RoomManager.GetChatRoom(roomId)` and then accesses the `MemberCount` property to get the latest number of participants. It also shows the necessary setup for the delegate. ```C# class RoomManagerDelegate : IRoomManagerDelegate { public void OnMemberJoinedFromRoom(string roomId, string participant, string ext) { int memberCount = SDKClient.Instance.RoomManager.GetChatRoom(roomId).MemberCount; } public void OnMemberExitedFromRoom(string roomId, string roomName, string participant) { } // 这里实现 IRoomManagerDelegate 中的其他功能 } RoomManagerDelegate roomManagerDelegate = new RoomManagerDelegate(); SDKClient.Instance.RoomManager.AddRoomManagerDelegate(roomManagerDelegate); ``` -------------------------------- ### Initialize EMClient SDK for iOS (Swift) Source: https://doc.easemob.com/document/ios/initialization This Swift code snippet demonstrates the fundamental steps to initialize the EMClient SDK. It involves creating an 'EMOptions' object with your application key and then calling 'initializeSDK' on the shared 'EMClient' instance. Placeholder comments indicate where additional 'EMOptions' configurations can be added. ```Swift let options = EMOptions(appkey: "Your appkey") ......// 其他 EMOptions 配置。 EMClient.shared().initializeSDK(with: options) ``` -------------------------------- ### Initialize ChatClient SDK with ChatOptions Object Source: https://doc.easemob.com/document/harmonyos/initialization Demonstrates the basic initialization of the ChatClient SDK using a ChatOptions object. It shows how to set the appKey and pass the context and options to the init method. ```JavaScript let options = new ChatOptions({ appKey: "你的 AppKey" }); ......// 其他 ChatOptions 配置。 // 初始化时传入上下文以及 options ChatClient.getInstance().init(context, options); ``` -------------------------------- ### cURL Example: Get Next Page of Users with Cursor Source: https://doc.easemob.com/document/server-side/account_system cURL command to retrieve the next page of users using a provided cursor for pagination. ```bash curl -X GET -H 'Accept: application/json' -H 'Authorization: Bearer ' 'https://XXXX/XXXX/XXXX/users?limit=2&cursor=LTgzXXXX2tB' ``` -------------------------------- ### Get User Notification Language Example Request Source: https://doc.easemob.com/document/server-side/push Example `curl` command to retrieve the preferred language for a user's push notifications. Replace `` with an actual app token. ```curl curl -L -X GET 'https://XXXX/XXXX/XXXX/users/XXXX/notification/language' \ -H 'Authorization: Bearer ' ``` -------------------------------- ### Easemob Flutter: Implement User Login Source: https://doc.easemob.com/document/flutter/quickstart Demonstrates how to log in a user with the Easemob Flutter SDK using a username and token. Includes basic input validation and robust error handling for network or SDK-related issues, logging outcomes to the console. ```Dart void _signIn() async { if (_username.isEmpty || _token.isEmpty) { _addLogToConsole("username or token is null"); return; } try { await EMClient.getInstance.loginWithToken(_username, _token); _addLogToConsole("sign in succeed, username: $_username"); } on EMError catch (e) { _addLogToConsole("sign in failed, e: ${e.code} , ${e.description}"); } } ``` -------------------------------- ### Initialize EaseMob Android SDK Source: https://doc.easemob.com/document/android/initialization This code snippet demonstrates the basic steps to initialize the EaseMob Android SDK. It involves creating an EMOptions object, setting the application key, and then calling the init method on the EMClient instance with the context and options. ```Java EMOptions options = new EMOptions(); options.setAppKey("Your appkey"); ......// 其他 EMOptions 配置。 EMClient.getInstance().init(context, options); ``` -------------------------------- ### cURL Example: Get Paginated User Friend List Source: https://doc.easemob.com/document/server-side/user_relationship A cURL command example demonstrating how to retrieve a user's paginated friend list. This example includes setting query parameters for limit and remark return, and specifying required headers like Content-Type, Accept, and Authorization. ```curl # 将 替换为你在服务端生成的 App Token curl -L -X GET 'https://XXXX/XXXX/XXXX/user/XXXX/contacts?limit=10&needReturnRemark=true' \ -H 'Content-Type: application/json' \ -H 'Accept: application/json' \ -H 'Authorization: Bearer ' ``` -------------------------------- ### Initialize EaseMob WebSDK Connection in JavaScript Source: https://doc.easemob.com/document/web/initialization This snippet demonstrates how to import the ChatSDK and initialize a new connection instance using the `ChatSDK.connection` constructor. The `appKey` parameter is crucial for identifying your EaseMob application. ```JavaScript import ChatSDK from "easemob-websdk"; const conn = new ChatSDK.connection({ appKey: "Your appKey", }); ``` -------------------------------- ### Create User using Easemob Server SDK in Java Source: https://doc.easemob.com/document/server-side/java_server_sdk This Java example demonstrates how to create a new user using the EMService. It shows how to call the user().create() method and handle potential EMException errors, including retrieving error codes and messages. The .block() method is used for synchronous execution. ```Java @Service public class UserService { @Autowired private EMService service; private void createUser() { try { EMUser user = service.user().create("username", "password").block(); } catch (EMException e) { e.getErrorCode(); e.getMessage(); } } } ```