logo
In-app Chat
SDK Error Codes
Powered Byspreading
On this page

Send and receive messages


This document describes how to use the ZIM SDK (In-app Chat) to send and receive messages.

Solution

The following shows the access solution that the ZIM SDK provides.

In this solution, you will need to implement the following business logic based on your actual business requirements:

  • The logic for managing the users on the client, and the logic for distributing user ID for users to log in.

Prerequisites

Before you begin, make sure:

  • Go to ZEGOCLOUD Admin Console, and do the following:

    • Create a project, get the AppID and AppSign.

    • Activate the In-app Chat service (as shown in the following figure).

  • Xcode 13 or later

  • A real iOS device that is running on iOS 11.0 or later and supports audio and video.

Integrate the SDK

Optional: Create a project

Skip this step if a project already exists.

Import the SDK

Choose either of the following methods to integrate the SDK into your project.

Method 1: Integrate the SDK automatically with Swift Package Manager

  1. Open Xcode and click "File > Add Packages..." in the menu bar, enter the following URL in the "Search or Enter Package URL" search box of the "Apple Swift Packages" pop-up window:

    Untitled
    https://github.com/zegolibrary/zim-ios
    
    1
    Copied!
  2. Specify the SDK version you want to integrate in "Dependency Rule" (Recommended: use the default rule "Up to Next Major Version"), and then click "Add Package" to import the SDK. You can refer to Apple Documentation for more details.

Method 2: Integrate the SDK automatically with CocoaPods

  1. Install CocoaPods. For more details, see CocoaPods Installation Guide .

  2. Open the Terminal, enter the root directory of the project, and execute the command pod init to create a Podfile.

  3. Open Podfile, add pod 'ZIM', and change MyProject to your target name.

    Warning

    Because the SDK is XCFramwork, therefore, you will need to use CocoaPods 1.10.0 or later to integrate the SDK.

    Untitled
    target 'MyProject' do
        use_frameworks!
        pod 'ZIM'
    end
    
    1
    Copied!
  4. Execute pod repo update to update the local index to make sure the latest version of SDK can be installed.

  5. Execute pod install to install the SDK.

    For common problems you may encounter when using CocoaPods, see CocoaPods FAQ .

Method 3: Manually add the SDK to the project

  1. Download the latest version of SDK from SDK downloads.

  2. Unzip the SDK package to the libs folder.

  3. Select the target project, click General, then under Frameworks, Libraries, and Embedded Content, add ZIM.xcframework to the target, and set the Embed field to Embed & Sign.

Implementation steps

Get the sample code

To download and run the sample code, see Sample app.

For the sample code related to this feature, check out the source files in the ZIMExampleLegacy/Peer/ZGPeerChatViewController.m directory in the SDK sample code package.

Import the header file

Import the header file ZIM.h.

Untitled
#import "ZIM/ZIM.h"
1
Copied!

Create a ZIM SDK instance

Creating a ZIM instance is the very first step, an instance corresponds to a user logging in to the system as a client.

So, let's suppose we have two clients now, client A and client B. To send and receive messages to each other, both of them will need to call the createWithAppConfig method with the AppID and AppSign you get in the previous Prerequisites steps to create a ZIM SDK instance of their own:

Warning

For SDK 2.3.0 or later, the AppSign authentication mode and Token-based authentication mode are both supported.

If you want to change your authentication mode, please refer to the Upgrade the authentication mode from using the AppSign to Token.

Untitled
// Create a ZIM SDK instance
//  Create a ZIM SDK object and pass your AppID and AppSign.
ZIMAppConfig *appConfig = [[ZIMAppConfig alloc] init];
appConfig.appID = (unsigned int)appID;
appConfig.appSign = @"appSign";
self.zim = [ZIM createWithAppConfig: appConfig];
1
Copied!

Conform to the EventHandler protocol

Before a client user's login, you will need to call the setEventHandler method to implement an event handler object that conforms to the ZIMEventHandler protocol (for example, self), and implement the methods involved in the protocol to receive callbacks (you can customize the event callbacks, such as you can receive callback notifications when SDK errors occur or receive message related callback notifications).

The following is the sample code for setting the event callback when connection status changes in the ViewContorller file:

Untitled
[zim setEventHandler:self];

- (void)zim:(ZIM *)zim errorInfo:(ZIMError *)errorInfo{
    // The callback for receiving error codes. This callback will be triggered when SDK returns error codes.
}

- (void)zim:(ZIM *)zim tokenWillExpire:(unsigned int)second{
    // The callback for Token expires. This callback will be triggered when the Token is about to expire, and you can customize a UI for this event.
}

- (void)zim:(ZIM *)zim connectionStateChanged:(ZIMConnectionState)state event:(ZIMConnectionEvent)event extendedData:(NSDictionary *)extendedData {
    // The callback for connection status changes. This callback will be triggered when the connection status changes, and you can customize a UI for this event.
}

- (void)zim:(ZIM *)zim
    peerMessageReceived:(NSArray<ZIMMessage *> *)messageList
                   info:(ZIMMessageReceivedInfo *)info
             fromUserID:(NSString *)fromUserID {
    // The callback for receiving one-to-one messages.
}
1
Copied!

Here’s the translation:

For a detailed introduction to the interfaces, please refer to tokenWillExpire, connectionStateChanged, and peerMessageReceived.

Log in to the ZIM SDK

For client A and client B to send and receive messages after creating the ZIM SDK instance, they will need to log in to the ZIM SDK.

To log in, Clients A and B both need to do the following:

  1. Call the ZIMUserInfo method to create a user object.
Warning
  • You can custom the userID and userName, and we recommend you set these two to a meaningful value and associate them with the account system of your application.

First, create a ZIMLoginConfig object with user login configurations. Then, client A and client B can call the loginWithUserID to log in to the ZIM SDK.

Notice
  • The “userID” and “userName” support custom rules defined by you. It is recommended that you set the “userID” to a meaningful value to associate it with your own account system.
  • If you are using “AppSign authentication” (default), please leave ZIMLoginConfig.Token empty.
  • If you are using “Token authentication,” please refer to the Using Token Authentication documentation. After obtaining the token, pass it in ZIMLoginConfig.Token when logging in to ZIM. You will only be able to log in successfully after the authentication is passed.
Untitled
// userID must be within 32 bytes, and can only contain letters, numbers, and the following special characters: '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '=', '-', '`', ';', '’', ',', '.', '<', '>', '/', '\'.
// userName must be within 256 bytes, no special characters limited.
ZIMLoginConfig *config = [[ZIMLoginConfig alloc]init];
config.userName = @"";

// When logging in: 
// If you are using the Token-based authentication mode, you will need to fill in the Token which you generated by referring to the [Authentication] doc.
// If you are using the AppSign mode for authentication (the default auth mode for v2.3.0 or later), leave the Token parameter blank. 
config.token = @"";

[zim loginWithUserID:userID config:config callback:^(ZIMError * _Nonnull errorInfo) {
    
}];
1
Copied!

Send messages

Client A can send messages to client B after logging in successfully.

Currently, the ZIM SDK supports the following message types:

Message TypeDescriptionFeature and Scenario
ZIMCommandMessage(2)The signaling message whose content can be customized. A signaling message cannot exceed 5 KB in size, and up to 10 signaling messages can be sent per second per client.

Signaling messages, unable to be stored, are applicable to signaling transmission (for example, co-hosting, virtual gifting, and course materials sending) in scenarios with a higher concurrency, such as chat rooms and online classrooms.

API: sendMessage

ZIMBarrageMessage(20)On-screen comments in a chat room. An on-screen comment cannot exceed 5 KB in size, and there is no number limit on comments that can be sent per second per client.

On-screen comments, unable to be stored are usually unreliable messages that are sent at a high frequency and can be discarded.

A high concurrency is supported, but reliability cannot be guaranteed.

API: sendMessage

ZIMTextMessage(1)The text message. A text message cannot exceed 32 KB in size, and up to 10 text messages can be sent per second per client.

Text messages are reliable, in order, and able to be stored as historical messages. (For the storage duration, please refer to Pricing - Plan Fee - Plan Differences).
It is applicable to one-to-one chats, group chats, and on-screen comments in chat rooms. After a room is disbanded, messages in it are not stored.

  • Images, files, audio, video: Typically used for sending rich media messages.
  • Custom message: Typically used for sending messages such as polls, chain messages, video cards, etc.
  • Multi-item Message: Typically used for sending a message including images and text.

API: sendMessagereplyMessage

ZIMMultipleMessage(10)Multi-item message, a message that can include multiple texts, up to 10 images, 1 file, 1 audio, 1 video, and 1 custom message.
Note
  • The total number of items should not exceed 20.
  • The size and format restrictions for images, audio, files, and videos are the same as those for the corresponding rich media message types.
ZIMImageMessage(11)Image message. Applicable formats includes JPG, PNG, BMP, TIFF, GIF, and WebP. The maximum size is 10 MB. Up to 10 image messages can be sent per second per client.
ZIMFileMessage(12)File Message. A file message contains a file of any format and cannot exceed 100 MB in size. Up to 10 file messages can be sent per second per client.
ZIMAudioMessage(13)Audio message. An audio message contains an MP3 or M4A audio of up to 300 seconds and cannot exceed 6 MB in size. Up to 10 audio messages can be sent per second per client.
ZIMVideoMessage(14)A video message contains an MP4 or MOV video and cannot exceed 100 MB in size. Up to 10 video messages can be sent per second per client.
Note
To retrieve the width and height of the first video frame after a video is successfully sent, the video must be encoded in H.264 or H.265.
ZIMCombineMessage(100)For combined messages, there is no limit on message size, and the sending frequency of a single client is limited to 10 times/second.
ZIMCustomMessage(200)You can customize the message type and parse the message without using the ZIM SDK.

To send one-to-one messages, for example, client A wants to send a message to client B, then client A needs to call the sendMessage method with client B's userID, message content, and other info. And client A can be notified whether the message is delivered successfully through the callback ZIMMessageSentCallback.

Moreover, the onMessageAttached callback can be received. The callback on the message not sent yet. Before the message is sent, you can get a temporary ZIMMessage message for you to implement your business logic as needed. For example, you can get the ID of the message before sending it. Or when sending a message with large content, such as a video, you can get the localMessageID of the message before the message is uploaded to implement a Loading UI effect.

Untitled
// The following shows how to send one-to-one message, the [conversationType] needs to be set to [ZIMConversationTypePeer].
ZIMTextMessage *zimMessage = [[ZIMTextMessage alloc]init];
zimMessage.message = @"Message content";
ZIMMediaMessageSendNotification *notification = [[ZIMMediaMessageSendNotification alloc] init];
notification.onMessageAttached = ^(ZIMMessage * _Nonnull message) {
    // The callback on the message not sent yet. You can get a temporary object here and this object must be the same as that created zimMessage object. You can make your own business logic using this as needed, for example, display a UI ahead of time.
};
ZIMMessageSendConfig *config = [[ZIMMessageSendConfig alloc] init];
config.priority = ZIMMessagePriorityMedium;  // Set priority for the message. 1: Low (by default). 2: Medium. 3: High.

// In 1-on-1 chats, the conversationID is the peer user ID. In group chats, the conversationID is the groupID. In the chat room, the conversationID is the roomID.
[zim sendMessage:zimMessage toConversationID:conversationID conversationType:ZIMConversationTypePeer config:config notification:notification callback:^(ZIMMessage * _Nonnull message, ZIMError * _Nonnull errorInfo) {
    // Implement the event callback on message sent.
    // toUserID refers to the userID of the message receiver.
}];
1
Copied!

Receive messages

After client B logs in, he will receive client A's message through the callback peerMessageReceived which is already set in the setEventHandler method.

Warning

When a message is received, you need to determine the message is a Text message or a Command message because these two message types are based on the basic message. You need to convert the basic message class to a concrete message type and then retrieve the message content from the Message field.

Untitled
- (void)zim:(ZIM *)zim
    peerMessageReceived:(NSArray<ZIMMessage *> *)messageList
                   info:(ZIMMessageReceivedInfo *)info
             fromUserID:(NSString *)fromUserID{
          for(ZIMMessage *message in messageList){
        if (message.type == ZIMMessageTypeText){
            ZIMTextMessage *textMessage = (ZIMTextMessage *)message;
        }
        else if (message.type == ZIMMessageTypeCommand){
            ZIMCommandMessage *commandMessage = (ZIMCommandMessage *)message;  
        }       
    }
1
Copied!

Log out

For a client to log out, call the logout method.

Untitled
[zim logout];
1
Copied!

Destroy the ZIM SDK instance

To destroy the ZIM SDK instance, call the destroy method.

Untitled
[zim destroy];
1
Copied!

Previous

Sample code

Next

SDK downloads