In-app Chat
  • iOS : Objective-C
  • Android
  • Web
  • Flutter
  • React Native
  • Unity3D
  • Windows
  • macOS
  • Introduction
    • Overview
    • Basic concepts
  • Sample app
  • Getting started
  • Client SDKs
    • SDK downloads
    • Release notes
    • Upgrade guide
  • Guides
    • Authentication
    • Manage users
    • Room
    • Group
    • Messaging
    • Call invitation (signaling)
    • Manage sessions
  • Offline push notifications
  • Error codes
  • Client APIs
  • Server APIs
  • Documentation
  • In-app Chat
  • Guides
  • Messaging
  • Send messages

Send & Receive messages

Last updated:2023-04-25 14:22

ZEGOCLOUD's In-app Chat (the ZIM SDK) provides the capability of message management, allowing you to send and receive one-to-one, group, in-room messages, query message history, delete messages, and more. With the message management feature, you can meet different requirements of various scenarios such as social entertainment, online shopping, online education, interactive live streaming, and more.

This document describes how to send and receive messages with the ZIM SDK.

Message types

Currently, the ZIM SDK supports the following message types:

Message type Description Details
ZIMTextMessage(1)
Text message. Size limit: 32 KB. Rate limit: 10 requests/second.
Enable messages to be more deliverable, and can be stored as message history. Suitable for one-on-one chat and group chat.
ZIMCommandMessage(2)
Customizable signaling message. Size limit: 5 KB. Rate limit: 10 requests/second.
Supports massive concurrency. Suitable for live audio room, online classroom, the messages won't be stored after the room is destroyed.
ZIMBarrageMessage(20)
In-room barrage message (bullet) screen message). Size limit: 5 KB. No specific rate limit.
The high-frequency messages that don't require 100% deliverability, this message type is often used to send bullet screen messages.

Supports massive concurrency, but the message deliverability can't be guaranteed.

ZIMImageMessage(11)
Image message. Supports major image formats, including JPG, PNG, BMP, TIFF, and GIF. Size limit: 10 MB. Rate limit: 10 requests/second.
Enable messages to be more deliverable, and can be stored as history messages. Suitable for one-on-one chat, room chat, and group chat.
ZIMFileMessage(12)
File message. Supports files in any format. Size limit: 100 MB. Rate limit: 10 requests/second.
ZIMAudioMessage(13)
Voice message. Supports voice messages in MP3 format within 300 seconds. Size limit: 6 MB. Rate limit: 10 requests/second.
ZIMVideoMessage(14)
Video message. Supports video messages in MP4 or MOV format. Size limit: 100 MB. Rate limit: 10 requests/second.

Prerequisites

  • Create a project in ZEGOCLOUD Console. Then, contact Technical Support to activate the In-app Chat service, and get the AppID and ServerSecret for SDK integration. The ZIM service permission is not enabled by default. Before using it, please activate the ZIM service by yourself in ZEGOCLOUD Console (for details, please refer to Project Management - In-app Chat), if you cannot activate the ZIM service, please contact ZEGOCLOUD technical support to activate it.
  • Get the Token that SDK required for login authentication. For details, see Authentication.
  • Integrate the ZIM SDK. For details, see the Integrate the SDK chapter of Send and receive messages.

Send/Receive regular messages

Regular messages refer to the messages of the following message types: ZIMTextMessage, and ZIMBarrageMessage.

  • To receive event callbacks (receive in-room messages, get the connection status, token expiration, etc.), you can set up the setEventHandler method and listen for related callbacks.
  • When receiving messages, you need to determine whether the message is a Text message (ZIMTextMessage) or a Command message (ZIMCommandMessage) because these two message types are based on the basic message class (ZIMMessage). You need to convert the basic message class to a concrete message type and then retrieve the message content from the message field.
  • When a message is received, it can be sorted using the message's orderKey. The larger the orderKey, the newer the message. And the number of unread messages will be updated automatically upon receiving.

Send messages

The following process shows how Client A sends messages to Client B:

  1. Client A and Client B create their own ZIM SDK instances, and set up an event handler setEventHandler to listen for the callback on the result of message sending receivePeerMessage.
  2. Client A and Client B log in to the ZIM SDK.
  3. Client A calls the sendMessage method, and set the converversationType to ZIMConversationTypePeer to send a one-to-one message to Client B.
  4. Client B listens for the receivePeerMessage callback to receive Client A's messages.

You can't send messages to yourself by calling the sendMessage method (when toConversationID = your ID). If you did so, the error code 6000001 will return.

Sample method call

- (void)sendMessage:(ZIMMessage *)message
    toConversationID:(NSString *)toConversationID
    conversationType:(ZIMConversationType)conversationType
              config:(ZIMMessageSendConfig *)config
        notification:(nullable ZIMMessageSendNotification *)notification
            callback:(ZIMMessageSentCallback)callback;

Parameter description

Parameter Type Required Description
message ZIMMessage * Yes Message content.
toConversationID NSString * Yes

Conversation ID. (ID of the receiver)

  • For one-on-one chat, it's the peer user's ID.
  • For group chats, it's the groupID.
  • For in-room chats, it's the roomID.
conversationType ZIMConversationType Yes

Conversation type.

  • 0: one-on-one chat
  • 1: In-room chat
  • 2: Group chat
config ZIMMessageSendConfig * Yes

Advanced configurations of the message to be sent:

notification ZIMMessageSendNotification Yes Callback on the message not sent yet: onMessageAttached, before the message is sent, you can get a temporary ZIMMessage message for you to implement your business logic as needed.
callback ZIMMessageSentCallback Yes Callback on the results of message sending.

Sample code

// 1. Create a ZIM SDK object with the AppID and AppSign you get.
ZIMAppConfig *appConfig = [[ZIMAppConfig alloc] init];
appConfig.appID = (unsigned int)appID;     // The AppID you get.
appConfig.appSign = @"appSign";     // The AppSign you get.
self.zim = [ZIM createWithAppConfig: appConfig];

// 2. Set up a setEventHandler.
[self.zim setEventHandler:self];

// 3. Log in
ZIMUserInfo *userInfo = [[ZIMUserInfo alloc] init];
userInfo.userID = @"xxxx";
userInfo.userName = @"xxxx";
[self.zim loginWithUserInfo:userInfo callback:^(ZIMError * _Nonnull errorInfo){
    // You can be told whether the login is successful according to the ZIMError.
}];

NSString *toConversationID = @"xxxx1";

ZIMTextMessage *textMessage = [[ZIMTextMessage alloc] init];
textMessage.message = @"Message content";

ZIMMessageSendConfig *config = [[ZIMMessageSendConfig alloc] init];
// Set the message priority.
config.priority = ZIMMessagePriorityLow;
// Set up the configurations of the offline notifications. To use this, enable this feature first. 
ZIMPushConfig *pushConfig = [[ZIMPushConfig alloc] init];
pushConfig.title = @"Offline notification title";
pushConfig.content= @"Offline notification content";
pushConfig.extendedData = @"Extension info of the offline notification";
config.pushConfig = pushConfig

ZIMMessageSendNotification *notification = [[ZIMMessageSendNotification alloc] init];
notification.onMessageAttached = ^(ZIMMessage * _Nonnull message) {
    // 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. 
};

// 4. Set conversation type. Set it based on your conversation type.
// Send one-on-one messages. 
ZIMConversationType type = ZIMConversationTypePeer;

// Send group messages. 
ZIMConversationType type = ZIMConversationTypeGroup;

// Send in-room messages.
ZIMConversationType type = ZIMConversationTypeRoom;

// 5. Send messages.
[self.zim sendMessage:textMessage toConversationID:toConversationID conversationType:type config:config notification:notification callback:^((ZIMMessage * _Nonnull message, ZIMError * _Nonnull errorInfo)) {
    // You can listen for this callback for the message sending results.
}];

Receive messages

Sample code

// Set up a ZIMEventHander and listen for related callbacks.
[zim setEventHandler:self];

// Callback for receiving the one-to-one message.
- (void)zim:(ZIM *)zim
    receivePeerMessage:(NSArray<ZIMMessage *> *)messageList
            fromUserID:(NSString *)fromUserID{
     // Implement your event handling logic after receiving the message here. 
}

// Callback for receiving the group message.
- (void)zim:(ZIM *)zim
    receiveGroupMessage:(NSArray<ZIMMessage *> *)messageList
            fromGroupID:(NSString *)fromGroupID{
    // Implement your event handling logic after receiving the message here. 
}

// Callback for receiving the in-room message.
- (void)zim:(ZIM *)zim
    receiveRoomMessage:(NSArray<ZIMMessage *> *)messageList
            fromRoomID:(NSString *)fromRoomID{
    // Implement your event handling logic after receiving the message here. 
}

Send/Receive rich media content

The ZIM SDK now supports sending and receiving messages of different rich media types, such as images, audio, video, and files. To send and receive rich media content, refer to the following:

  1. To send rich media content after login, you will need to specify the message type (image, file, audio, video) first and then the session type (one-on-one chat, room chat, group chat).
  2. For a receiver to receive and download the rich media content, set up and listen for related event callbacks based on the session type (one-on-one chat, room chat, group chat) after logging in.

Send rich media content

To send rich media content after login, call the sendMediaMessage method, and specify the message type (image, file, audio, video), the session type (one-on-one chat, room chat, group chat), and message related configurations as needed.

  • When sending rich media content, the file path to be sent must be in UTF-8 encoding format.
  • To send rich media content to a room/group, the sender must be in the room/group.

Sample method call

- (void)sendMediaMessage:(ZIMMediaMessage *)message
        toConversationID:(NSString *)toConversationID
        conversationType:(ZIMConversationType)conversationType
                  config:(ZIMMessageSendConfig *)config
                progress:(ZIMMediaUploadingProgress)progress
                callback:(ZIMMessageSentCallback)callback;

Parameter description

Parameter Type Required Description
message ZIMMediaMessage * Yes Rich media content to be sent.
toConversationID NSString * Yes

Session ID.

  • In one-on-one chat, conversationID is the peer side's userID.
  • In group chat, conversationID is the groupID.
  • In room chat, the conversationID is the roomID.
conversationType ZIMConversationType Yes

Session type.

  • 0: One-on-one chat
  • 1: Room chat
  • 2: Group chat
config ZIMMessageSendConfig * Yes Advanced configurations of the message to be sent.
notification ZIMMediaMessageSendNotification Yes

Callbacks:

  • onMediaUploadingProgress, callback on the progress of sending messages.
  • onMessageAttached, 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.
callback ZIMMessageSentCallback Yes Callback for the results of send rich media content.

Sample code

// Send rich media content in one-on-one chat - Send images:
ZIMImageMessage *imgMsg = [[ZIMImageMessage alloc] init];

// Fill in a UTF-8 local path (the path to the local picture is recommended)
// The following uses a temporary image path as an example:
imgMsg.fileLocalPath = @"/private/var/mobile/Containers/Data/Application/C142EFE6-9DEC-449D-89B7-BF99F2578F98/tmp/D1513E30-2641-440B-B897-48CD43BE1D04.jpeg";

// If a network URL is entered here, the SDK will pass through the path without ZIM background service processing. If both the network URL and the local path are entered, the SDK will prioritize the network URL that you want to use.
imgMsg.fileDownloadUrl = @"";

ZIMMessageSendConfig *sendConfig = [[ZIMMessageSendConfig alloc] init];
sendConfig.priority = 1;

ZIMMediaMessageSendNotification *notification = [[ZIMMediaMessageSendNotification alloc] init];
notification.onMessageAttached = ^(ZIMMessage * _Nonnull message) {
    // Implement your event handling logic before the message is sent. 
};

notification.onMediaUploadingProgress = ^(ZIMMediaMessage * _Nonnull message, unsigned long long currentFileSize, unsigned long long totalFileSize) {
    // You can listen for the callback to know the progress of the rich media message you sent.
};

[[ZIM getInstance] sendMediaMessage:imgMsg toConversationID:@"conversationID" conversationType:ZIMConversationTypePeer config:sendConfig notification:notification callback:^(ZIMMessage * _Nonnull message, ZIMError * _Nonnull errorInfo) {

}];

Callback for the sending progress of rich media content

You will be notified of the sending progress of rich media content through the callback onMediaUploadingProgress of the ZIMMediaMessageSendNotification method.

Sample method call

typedef void (^ZIMMediaUploadingProgress)(ZIMMessage *message, unsigned long long currentFileSize, unsigned long long totalFileSize);

Among which:

  • message: The content of the message being sent.
  • currentFileSize: The size of the message that has been sent.
  • totalFileSize: The overall size of the message sent.

Receive rich media content

To receive the rich media content messages, do the following:

  1. Listen for the following callbacks based on the session type (one-on-one chat, room chat, group chat): receivePeerMessage,receiveRoomMessage, receiveGroupMessage.
  2. Call the downloadMediaFileWithMessage method to download the rich media content.

When downloading rich media content, you need to specify the file type of the corresponding media messages first.

  • Image messages: You can choose to download the original file, large view, or thumbnail.
  • Files/Audio messages: Only original files/audio files can be downloaded.
  • Video messages: You can choose to download the original video file and the thumbnail of the first frame of the video.

Sample method call

- (void)downloadMediaFileWithMessage:(ZIMMediaMessage *)message
                            fileType:(ZIMMediaFileType)fileType
                            progress:(ZIMMediaDownloadingProgress)progress
                            callback:(ZIMMediaDownloadedCallback)callback;

Parameter description

Parameter Type Required Description
message ZIMMediaMessage * Yes Received rich media content.
fileType ZIMMediaFileType Yes

The file type of the received rich media content.

  • 1: The raw files of rich media content.
  • 2: The larger view of the image message.
  • 3: The thumbnail of the image message.
  • 4: The first frame image of the video file.
progress ZIMMediaDownloadingProgress Yes The progress of downloading messages.
callback ZIMMediaDownloadedCallback Yes Callback for the results of download rich media content.

Sample code

// Receive rich media content in one-on-one chat - Receive images 
- (void)receivePeerMessage:(NSArray<ZIMMessage *> *)messageList
                fromUserID:(NSString *)fromUserID{
    for (ZIMMessage *msg in reverseMsgList) {

        // You can tell by the Type which kind of message you are receiving. 
        switch (msg.type) {
            case ZIMMessageTypeImage:{
                ZIMImageMessage *imageMsg = (ZIMImageMessage *)msg;
                [[ZIM getInstance] downloadMediaFileWithMessage:imageMsg fileType:ZIMMediaFileTypeOriginalFile progress:^(ZIMMessage * _Nonnull message, unsigned long long currentFileSize, unsigned long long totalFileSize) {

                            } callback:^(ZIMMessage * _Nonnull message, ZIMError * _Nonnull errorInfo) {

                }];
                break;
            }
            case ZIMMessageTypeVideo:{
                ZIMVideoMessage *videoMsg = (ZIMVideoMessage *)msg;
                break;
            }
            case ZIMMessageTypeAudio:{
                ZIMAudioMessage *audioMsg = (ZIMAudioMessage *)msg;
                break;
            }
            case ZIMMessageTypeFile:{
                ZIMFileMessage *fileMsg = (ZIMFileMessage *)msg;
                break;
            }
            default:
                break;
        }

    }
}

Callback for the downloading progress of rich media content

You will be notified of the downloading progress of rich media content through the callback ZIMMediaDownloadingProgress.

Sample method call

typedef void (^ZIMMediaDownloadingProgress)(ZIMMessage *message, unsigned long long currentFileSize, unsigned long long totalFileSize);

Among which:

  • message: The message content you are downloading.
  • currentFileSize: The size of messages that have been downloaded.
  • totalFileSize: The overall size of the download message.

Send/Receive custom messages

The ZIM SDK now supports you to send and receive custom messages. To do that, you can call the ZIMCommandMessage to define the message type you want to send, for example, your location information.

The following shows how to send custom messages to a specified user.

Send custom messages

Sample code

// Send custom messages to a specified user.
NSData *anyData = [[NSData alloc] init];
NSString *toUserID = @"toUserID";
ZIMCommandMessage * cmdMsg = [[ZIMCommandMessage alloc] initWithMessage:anyData];
ZIMMessageSendConfig *sendConfig = [[ZIMMessageSendConfig alloc] init];
sendConfig.priority = ZIMMessagePriorityMedium;

[self.zim sendMessage:cmdMsg toUserID:toUserID conversationType:type config:config notification:notification callback:^((ZIMMessage * _Nonnull message, ZIMError * _Nonnull errorInfo)) {
    // You can listen for this callback on the results of the message sending.
}];

Receive custom messages

Sample code

// Receive custom messages.
- (void)zim:(ZIM *)zim receivePeerMessage:(NSArray<ZIMMessage *> *)messageList fromUserID:(NSString *)fromUserID {
    if (zim != self.zim) {
        return;
    }
    for (ZIMMessage *msg in messageList) {
        if(msg.type == ZIMMessageTypeCommand){
            ZIMCommandMessage *cmdMsg = (ZIMCommandMessage *)msg;
            NSData *receivedData = cmdMsg.message;
        }
    }
}

Listen for the message status

On a weak network condition, this may happen: the ZIM SDK doesn't receive the response from the server for some reason (e.g., packet loss), while the message is successfully sent. In this case, the ZIM SDK considers the message sending failed due to the reply timeout, but the message is actually sent successfully, which results in message status confusion. To solve this and Clarify the message status, the SDK 2.6.0 or later now allows you to listen for the messageSentStatusChanged callback to receive the changes of the message status. And we now have three different message statuses: Sending, Success, and Failed. You can know whether your message is sent successfully by the status, and implement your event handling logic as needed.

//  Listen for the message status.
- (void)zim:(ZIM *)zim messageSentStatusChanged:
        (NSArray<ZIMMessageSentStatusChangeInfo *> *)messageSentStatusChangeInfoList {
            // You can listen for the callback on the changes of message status here.
}
Page Directory