Skip to main content

Quick Start (Swift)

This tutorial helps developers quickly understand and master the basic integration process and core capabilities of the IMKit SDK (RC Chat UI library). Through this guide, you'll complete the full workflow of importing the IMKit SDK via Swift, initializing it, establishing connections, displaying conversation lists and chat UIs, and testing message sending/receiving.

Environment Requirements

  • Xcode 11 or later
  • iOS 9.0 or later
  • Swift 5.0 or later
  • CocoaPods 1.10.0 or later (if using CocoaPods integration). Note: IMLib SDK versions after 5.1.1 switched to XCFramework format, which requires CocoaPods 1.10.0+ for full support. See Knowledge Base.

To install CocoaPods, refer to CocoaPods Installation.

Prerequisites

  1. Register a developer account on the RC Console. Upon successful registration, the console automatically creates an application in your development environment.
  2. Obtain your AppKey from the Basic Info page in the console. You can view application details including App Key, App Secret, and data center location (default: Beijing).

To create applications manually, see How to Create an App and Obtain App Key/Secret.

tip

Each app has two distinct App Keys for development and production environments, with data isolation between them. Before official launch, switch to the production App Key for full testing. :::

Importing the SDK

RC supports both remote dependency via CocoaPods and local XCFramework integration. This example demonstrates CocoaPods remote dependency.

tip

Starting from version 5.16.1, IMKit SDK also supports Swift Package Manager integration.

CocoaPods Integration

  1. If your project lacks a Podfile, run pod init in your project root directory, then add to the generated file:

    pod 'RongCloudIM/IMKit', '~> x.y.z'
    tip

    Replace x.y.z with the actual version number. Check the latest version on the RC SDK Download Page or via pod search RongCloudIM after running pod repo update.

  2. Run in terminal:

    pod install
    tip

    If encountering version conflicts, run pod repo update before pod install.

  3. Open the generated .xcworkspace file in Xcode.

Initializing the SDK

Import the SDK header:

import RongIMKit

Initialize IMKit SDK using your AppKey. For Beijing Data Center (default), no RCInitOption configuration is needed:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

let appKey: String = "Your_AppKey" // example: bos9p5rlcm2ba
let option: RCInitOption? = nil
RCIM.shared().initWithAppKey(appKey, option: option)

return true
}

For global data centers, specify the AreaCode:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

let appKey: String = "Your_AppKey" // example: bos9p5rlcm2ba
let option: RCInitOption? = RCInitOption.init();
option?.areaCode = .SG;
RCIM.shared().initWithAppKey(appKey, option: option)
return true
}
tip

For IMKit SDK development versions below 5.4.2 or stable versions ≤5.3.8, use initWithAppKey directly. See Initialization.

Connecting to RC IM Server

Token is the unique authentication credential corresponding to user IDs. Clients must establish an IM connection using a valid Token before using RC services.

In production, obtain Tokens via your application server calling IM Server API. See User Registration.

For testing purposes, use the Console's Polaris developer tools to call the Get Token API. Example response for userId=1:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8

{"code":200,"userId":"1","token":"gxld6GHx3t1eDxof1qtxxYrQcjkbhl1V@sgyu.cn.example.com;sgyu.cn.example.com"}
  1. Set connection status listeners for real-time monitoring. Recommended to set listeners after SDK initialization but before connection. See Connection Status Monitoring.
import UIKit
import RongIMKit

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
connectRongcloud()
}

func connectRongcloud() {
/*
Set connection delegate before connecting.
*/
RCIM.shared().addConnectionStatusDelegate(self)
}
/*
IMKit Connection Status Delegate
*/
extension ViewController: RCIMConnectionStatusDelegate {
func onRCIMConnectionStatusChanged(_ status: RCConnectionStatus) {

}
}
}
  1. Connect using connectWithToken. Note: IMKit SDK has auto-reconnect; call connect once per app lifecycle. See Connection.
RCIM.shared().connect(withToken: "your_token") { dbErrorCode in
// Database ready

} success: { (userId: String?) in
/* Connection successful - navigate to conversation list */
DispatchQueue.main.async { [weak self] in
self?.openRongcloudConversationList()
}

} error: { (connectStatus: RCConnectErrorCode) in
if connectStatus == .RC_CONN_TOKEN_INCORRECT {
/* Get new token from app server and reconnect */
} else {
/* Handle other connection errors */
}
}

RCConnectErrorCode defines possible connection error codes:

Error CodeValueDescriptionSolution
RC_CONN_TOKEN_INCORRECT31004Invalid Token. Typically occurs when client SDK and app server use different App Keys.Verify App Key consistency.
RC_CONN_TOKEN_EXPIRE31020Token expired.Request new Token from app server.
RC_CONNECT_TIMEOUT34006Auto-reconnect timeout. Occurs in no-network environments.Manual reconnect
RC_CONN_APP_BLOCKED_OR_DELETED31008AppKey blockedCheck AppKey status
RC_DISCONN_KICK31010Kicked offline after successful connectionShow logout prompt
RC_CONN_OTHER_DEVICE_LOGIN31023Logged in on another deviceShow multi-device login alert
RC_CONN_USER_BLOCKED31009User bannedShow ban notice
RC_CLIENT_NOT_INIT33001SDK not initializedCall Init first
RC_INVALID_PARAMETER33003Invalid parametersVerify parameter types/values
DATABASE_ERROR33002Database errorCheck userId for special characters (max 64 chars, alphanumeric only)

RCConnectionStatus defines connection status codes:

Status CodeValueDescription
ConnectionStatus_KICKED_OFFLINE_BY_OTHER_CLIENT6Kicked by another device
ConnectionStatus_Timeout14Auto-connect timeout
ConnectionStatus_TOKEN_INCORRECT15Invalid Token (wrong or expired)
ConnectionStatus_DISCONN_EXCEPTION16Disconnected (user banned)

Displaying Conversation List

IMKit SDK provides default conversation list UI (RCConversationListViewController). After successful connection, navigate to this view. For first-time users, the list may appear empty until receiving messages.

Example navigation implementation (adapt if already using navigation controllers):

private func openRongcloudConversationList() {
let displayConversationTypeArray = [
RCConversationType.ConversationType_PRIVATE.rawValue,
RCConversationType.ConversationType_GROUP.rawValue,
]
let collectionConversationType = [
RCConversationType.ConversationType_SYSTEM.rawValue
]
guard let conversationList = RCConversationListViewController(displayConversationTypes: displayConversationTypeArray,
collectionConversationType: collectionConversationType) else { return }
let naviVC = UINavigationController(rootViewController: conversationList)
naviVC.modalPresentationStyle = .fullScreen
present(naviVC, animated: false)
}
tip

For customization, subclass RCConversationListViewController (e.g., RCDChatListViewController).

//
// RCDChatListViewController.swift
// RongcloudApplication
//

import Foundation
import RongIMKit

class RCDChatListViewController: RCConversationListViewController {

}

Details: Conversation List, Conversation UI.

Testing Messaging

RC enables messaging by simply specifying the recipient's userId. For testing, use Console's Polaris tools to send test messages.

  1. Navigate to IM Server API Debug in Console.

  2. Under Message Service, find Send Private Message.

    Example: Send text message from userId=2 to userId=1.

    message sent from console

  3. Received messages automatically appear in the conversation list. Tap to enter chat UI.

    alt(width=250) alt(width=250)

    tip

    Screenshots show SealTalk UI. Default IMKit implementation shows basic list without search/Tab Bar. For nicknames/avatars, implement user info providers (see User Overview).

Next Steps

This completes basic IM integration. Explore these advanced topics: