Send your first message
This quickstart walks you through the core integration flow of the Nexconn Chat SDK: importing the SDK, initializing it, setting up event handlers, connecting to the server, and sending a message.
Requirements
- Xcode 14.0 or later
- iOS 13.0 or later
- CocoaPods 1.10.0 or later (if using CocoaPods)
To install CocoaPods, see Installing CocoaPods.
Prerequisites
- Register a developer account on the Nexconn Console. A default application is automatically created in the development environment upon registration.
- On the Key Management page, obtain your App Key for the development environment. You can also view the App Secret and data center assignment (Singapore by default).
You can also create a new application and get the App Key and App Secret for the environment you want to use.
Each application has two separate App Keys for the development and production environments. Data is isolated between environments. Before going live, switch to the production App Key to complete end-to-end testing.
Step 1: Import the SDK
Nexconn supports CocoaPods remote dependencies, Swift Package Manager, and manual XCFramework imports.
This quickstart uses CocoaPods. For all import options, see Import the SDK.
-
If your project doesn't have a
Podfile, open a terminal, navigate to the project root, and runpod init. Then add the following to the generatedPodfile:rubypod 'NexconnChat/Chat', '~> x.y.z'tipReplace
x.y.zwith the latest version. Runpod repo updatethenpod search NexconnChatSDKto find the latest version. -
In the terminal, navigate to the
Podfiledirectory and run:shellpod installtipIf you see errors like
CocoaPods could not find compatible versions for, runpod repo updatefirst, then retrypod install. -
Open the
.xcworkspacefile in Xcode to load the project.
Step 2: Initialize the SDK
Import the SDK in Swift, or use the Objective-C header if your app target still integrates the SDK that way:
- Swift
- Objective-C
import NexconnChatSDK
#import <NexconnChatSDK/NexconnChatSDK.h>
Call the init method to initialize the Chat SDK. Before initializing, obtain your App Key from the Nexconn Console and configure NCInitParams.
This quickstart demonstrates basic initialization. For full options including data center configuration, see Initialize the SDK.
NCInitParams accepts the following optional properties: areaCode (data center region code), naviServer (navigation service URL), and logLevel (log level).
The SDK connects to Singapore by default. If you use the Singapore data center, you don't need to configure NCInitParams.
- Swift
- Objective-C
import NexconnChatSDK
let appKey = "Your_AppKey" // example: bos9p5rlcm2ba
NCEngine.initialize(InitParams(appKey: appKey))
NSString *appKey = @"Your_AppKey"; // example: bos9p5rlcm2ba
[NCEngine initializeWithParams:[[NCInitParams alloc] initWithAppKey:appKey]];
If you use an overseas data center, pass the corresponding AreaCode:
- Swift
- Objective-C
import NexconnChatSDK
let appKey = "Your_AppKey" // example: bos9p5rlcm2ba
let initOption = InitParams(appKey: appKey)
initOption.areaCode = .sg
NCEngine.initialize(initOption)
NSString *appKey = @"Your_AppKey"; // example: bos9p5rlcm2ba
NCInitParams *initOption = [[NCInitParams alloc] initWithAppKey:appKey];
initOption.areaCode = NCAreaCodeSg; // Singapore data center
[NCEngine initializeWithParams:initOption];
Step 3: Listen for messages
Register a message handler to receive all real-time and missed messages.
To ensure you receive all missed messages, register the message handler after initializing the SDK but before connecting to the server.
- Swift
- Objective-C
import NexconnChatSDK
final class MyMessageHandler: NSObject, MessageHandler {
func onMessageReceived(_ event: MessageReceivedEvent) {
print("Message received: \(event.message?.content ?? "")")
}
}
let messageHandler = MyMessageHandler()
NCEngine.addMessageHandler(identifier: "MyMessageHandler", handler: messageHandler)
// Register a message handler (the identifier must be globally unique; typically use the class name)
[NCEngine addMessageHandlerWithIdentifier:@"MyMessageHandler" handler:self];
// Implement the NCMessageHandler protocol
- (void)onMessageReceived:(NCMessageReceivedEvent *)event {
NSLog(@"Message received: %@", event.message.content);
}
Step 4: Connect to the server
An access token is a user-specific authentication credential that uniquely identifies a user within the Nexconn platform. Your app client must establish a connection with the token before using any messaging features.
In production, your app server should call the IM Server API to obtain the token. See Register a user.
For this quickstart, use Postman to call the Nexconn Server API directly.
Obtain an access token with Postman
Step 1: Prepare your App Key and App Secret
Log in to the Nexconn Console and obtain your App Key and App Secret from the application details page.
Step 2: Configure the request in Postman
- Create a new POST request.
- Request URL:
<data-center-url>/v4/auth/access-token/issue - Set the request headers:
App-Key: Your App KeyNonce: A random number, e.g.14314Timestamp: Current timestamp in milliseconds, e.g.1708588800000Signature: Computed signature (see below)Content-Type:application/json
- Set the request body (raw JSON):
userId: A user ID, e.g.user001name: A display name, e.g.Test UseravatarUrl: (Optional) A user avatar URI
Step 3: Compute the signature
Signature formula: SHA1(AppSecret + Nonce + Timestamp)
Example:
- App Secret:
your_app_secret - Nonce:
14314 - Timestamp:
1708588800000 - Concatenated string:
your_app_secret143141708588800000 - Compute the SHA1 hash as the Signature
You can use any online SHA1 tool, or refer to the Server API signature rules.
Step 4: Send the request
Click Send. A successful response looks like:
{
"code": 0,
"result": {
"userId": "user123",
"accessToken": "FuK+jwXeNx1AblU0QxYLi233zkQsbE8eVSFdUMVanNsEdhXOODvIdVve0DXq6Vasrlxp63siueSQy5N94o70MzwM8cj754Iz"
}
}
Save the token value. You'll need it to connect to the server.
- Never call Server APIs directly from the client in production. This would expose your App Key and App Secret, creating a serious security risk.
- Always obtain and distribute tokens through your own app server.
Set up a connection status listener
Set up a connection listener to track connection status in real time. You can reflect connection states in the UI, such as "Network disconnected" or "Reconnected." Register the listener after initialization and before connecting.
- Swift
- Objective-C
let status = NCEngine.getConnectionStatus()
// Query the current connection status
NCConnectionStatus status = [NCEngine getConnectionStatus];
Connect to the server
Call connectWithParams:databaseOpenedHandler:completionHandler: to connect to the Nexconn server using the access token.
The Chat SDK has a built-in reconnection mechanism. You only need to call connectWithParams: once per app lifecycle.
- Swift
- Objective-C
import NexconnChatSDK
let params = ConnectParams(token: "Your_Token")
NCEngine.connect(
params: params,
databaseOpenedHandler: { isRecreated, error in
guard error == nil else { return }
// Database opened — navigate to the main screen
if isRecreated {
// Local data was cleared
}
},
completionHandler: { userId, error in
if let error {
print("Connection failed: \(error.localizedDescription)")
} else {
print("Connected successfully, userId: \(userId ?? "")")
}
}
)
NCConnectParams *params = [[NCConnectParams alloc] initWithToken:@"Your_Token"];
[NCEngine connectWithParams:params
databaseOpenedHandler:^(BOOL isRecreated, NCError * _Nullable error) {
// Database opened — navigate to the main screen
// isRecreated == YES means local data was cleared
} completionHandler:^(NSString * _Nullable userId, NCError * _Nullable error) {
if (error == nil) {
NSLog(@"Connected successfully, userId: %@", userId);
} else {
NSLog(@"Connection failed: %@", error);
}
}];
Step 5: Send a message
Send a text message to the user with userId 2. Beyond text, you can also send images, files, voice messages, and other message types. See Message types for details.
- Swift
- Objective-C
import NexconnChatSDK
let messageContent = TextMessage(text: "Hello, this is a message from User 1")
guard let channel = DirectChannel(channelId: "2") else {
return
}
let params = SendMessageParams(content: messageContent)
channel.sendMessage(params: params, attachedHandler: nil) { message, error in
if let error {
print("Failed to send message: \(error.localizedDescription)")
} else {
print("Message sent: \(message?.messageId ?? "")")
}
}
NCTextMessage *messageContent = [[NCTextMessage alloc] initWithText:@"Hello, this is a message from User 1"];
NCDirectChannel *channel = [[NCDirectChannel alloc] initWithChannelId:@"2"];
NCSendMessageParams *params = [[NCSendMessageParams alloc] initWithContent:messageContent];
[channel sendMessageWithParams:params
attachedHandler:nil
completionHandler:^(NCMessage * _Nullable message, NCError * _Nullable error) {
if (error == nil) {
NSLog(@"Message sent: %@", message.messageId);
} else {
NSLog(@"Failed to send message: %@", error);
}
}];