Instant Messaging
iOS
Getting Started
Product Introduction
Overview
Features
Feature overview
Account Integration and Login
Basic Message Features
Group Chat
Chat Room
Chat Room Tags
Multi-device Login
Statistics Monitoring
Limits
Development Integration
Message Sending
Message Receiving
Recent Chats
Server Sessions
User Profile
User Relationship
Online Status Subscription
System Notification
APNs
Superteam
Chat Room
Anti-spam
Chat Extension
Miscellaneous Features
Reference Documents
Configuration Instruction for PushKit
Push Configuration for Apple iOS
API References
iOS API Reference
Status Codes

Receiving Messages

Update time: 2021/12/06 15:01:02

Receive messages

For information about sending messages, see Sending messages. When a message is received, the upper level will be notified with the callback function of chatManager:

Prototype

@protocol NIMChatManagerDelegate <NSObject>
- (void)onRecvMessages:(NSArray<NIMMessage *> *)messages
@end

Parameter List

Parameter Type Description
messages NSArray<NIMMessage *> A set of messages, which are arranged in chronological order and located in the same session.

Receive notification messages

For specific scenarios, CommsEase server presets some notification messages. The notification is also a specific message. The developer needs to parse the information in a message to get the notification content. The most common notification message is a team notification event, for example, if a new member joins to a team, all members of the team will receive the notification message. The notification message can not be sent from the client now.

Attachment prototype:

@interface NIMNotificationObject : NSObject<NIMMessageObject>
/**
 * The content of a notification message
 */
@property (nonatomic,strong,readonly) NIMNotificationContent *content;

/**
 * The type of a notification message
 */
@property (nonatomic,assign,readonly) NIMNotificationType notificationType;
@end

Parameter List

Parameter Type Description
content NIMNotificationContent The content of a notification
notificationType NIMNotificationType Notification type: notification type will be extended with SDK upgrade, so the developer should consider the compatibility after the upgrade

Notification types. The specific notification type varied with the specific SDK version. Therefore, developers need to consider the compatibility issues of upgraded SDK versions.

Parse a notification message as follows:

  • Resolve the messageObject field in NIMMessage into NIMNotificationObject in a strong type.
  • Resolve the content field in NIMNotificationObject to get the parent class NIMNotificationContent.
  • Based on the notificationType field in NIMNotificationContent, strongly type the parent class NIMNotificationContent into a specific subtype

All types of content are as follows:

Notification types NIMNotificationContent
Team events NIMTeamNotificationContent
VOIP NIMNetCallNotificationContent
Chat rooms NIMChat roomNotificationContent
Unsupported NIMUnsupportedNotificationContent

For information on NIMTeamNotificationContent, see Notification messages in a team.

Receive multi-media messages

The multi-media messages include audio, image, file, and video messages. You should consider downloading resources after receiving a message. For multi-media messages that are uploaded by using CommsEase service:

  • If image and video messages are received, by default, the SDK will automatically download thumbnails and cover image when receiving a message.
  • If audio messages are received, by default, the SDK will automatically download the original audio file when receiving the message.
  • If file messages are received, the SDK will not download the original file.

To disable the default policy and download messages as required, do as follows:

  • Disable the automatic download:

SetfetchAttachmentAutomaticallyAfterReceivingandfetchAttachmentAutomaticallyAfterReceivingInChat roominNIMSDKConfigasNO.

@interface NIMSDKConfig <NSObject>
/**
* Specifies whether to automatically download attachments after receiving a message in a team chat or a one-to-one chat. By default, the value is set as "YES". The SDK will download message attachments when receiving a message for the first time. The upper-level developers can make configurations as required.
*/
@property (nonatomic, assign) BOOL fetchAttachmentAutomaticallyAfterReceiving

/**
* Specifies whether to automatically download attachments after receiving the chat room message. By default, the value is set as "NO".
*/
@property (nonatomic, assign) BOOL fetchAttachmentAutomaticallyAfterReceivingInChat room
@end                         
  • Manually download attachments:
@protocol NIMChatManager <NSObject>
- (BOOL)fetchMessageAttachment:(NIMMessage *)message
                         error:(NSError **)error
@end                         

Parameter List

Parameter Type Description
message NIMMessage Messages that require an attachment
error NSError Throw an error object

Download attachments, and you will be notified by a callback of the process of downloading attachments.

  • Cancel downloading specified messages:
@protocol NIMChatManager <NSObject>
- (void)cancelGetingMessageAttachment:(NIMMessage *)message;
@end

Attachments include thumbnails for image messages, video messages, audio messages, file messages, and custom messages.

Considerations:

For image and video messages uploaded by CommsEase, you can download the thumbnails and cover images are downloaded by using the above method. If you want to download the original videos and images, you can import the parameters URL and path of an attachment object in the following ways to download the original files.

@protocol NIMResourceManager <NSObject>
/**
* @param URLString - The Downloaded URL
* @param filepath - The download path
* @param progress - Progress Block
* @param completion - Completion Block
*/
- (void)download:(NSString *)URLString 
        filepath:(NSString *)filepath 
        progress:(nullable NIMHttpProgressBlock)progress 
      completion:(nullable NIMDownloadCompleteBlock)completion;
@end                         

For more information on methods of NIMResourceManager, see the client API documentation.

Receiving messages in a chat room

A chat room is a scenario with a large volume of messages. Therefore, when receiving messages, the SDK will wait for a while to report the messages in batches after receiving a message package. So, over-frequent callbacks are avoided.

Besides, considering that inconsistent business logic makes API processing different, if the developer still believes that over-frequent message insertion leads to API lag, you can construct a to-be-inserted message pool in the upper layer, while creating a sub-thread to compute typesetting. For more information on the specific logic, see the demo of processing chat room messages.

Message filtering

SDK supports message filtering. After the message filtering, the SDK will neither store the corresponding message nor throw it to the receiving callback, so the application layer will not receive the corresponding message.

Message filtering is only valid for online messages, offline messages, roaming messages, and other messages.During a query, local and cloud histories are unfilterable.

We do not recommend executing for a long time when using the message filtering function or method; otherwise, the thread may be blocked.

When initializing the SDK, create a NIMSDKConfigDelegate object, and assign this object to the delegate property of NIMSDKConfig in the following ways.

  • -(BOOL)shouldIgnoreNotification:(NIMNotificationObject *)notificationMethod: if YES is returned, it means that a notification message is ignored.
  • -(BOOL)shouldIgnoreMessage:(NIMMessage *)messageMethod: if YES is returned, it means that an ordinary message is ignored.

Broadcast message receiving

CommsEase supports broadcasting messages to all users, which are initiated by the server API, and a broadcast message is sent to all the users in the application. The client cannot send any messages. The SDK receives the broadcast and sends a notification to the upper layer. The message cannot be stored on the client.

API prototype

@protocol NIMBroadcastManager <NSObject>

/**
 * Add delegation of a broadcast message
 *
 * @param delegate - A callback for broadcast message
 */
- (void)addDelegate:(id<NIMBroadcastManagerDelegate>)delegate;

/**
 * Remove delegation of a broadcast message
 *
 * @param delegate - A callback for broadcast message
 */
- (void)removeDelegate:(id<NIMBroadcastManagerDelegate>)delegate;

@end

Parameter List

Parameter Type Description
delegate id Broadcast notification callback object

Callback prototype

@protocol NIMBroadcastManagerDelegate <NSObject>

/**
 * A callback for receiving a broadcast message
 *
 * @param broadcastMessage - Broadcast message
 */

- (void)onReceiveBroadcastMessage:(NIMBroadcastMessage *)broadcastMessage;
@end

Parameter List

Parameter Type Description
broadcastMessage NIMBroadcastMessage Broadcast message

System broadcast NIMBroadcastMessage prototype

Parameter List

Parameter Type Description
broadcastId int64_t System broadcast id, globally unique
sender NSString Sender id
timestamp NSTimeInterval Time
content NSString Content

Example

// Add monitoring
- (void)addListener
{
   [[NIMSDK sharedSDK].broadcastManager addDelegate:self];
}

...

// Callback method
- (void)onReceiveBroadcastMessage:(NIMBroadcastMessage *)broadcastMessage
{
    //do something with broadcast message
}

Audio message processing

For audio messages, the SDK encapsulates the methods of recording and playing for developers' use. Multimedia administrator NIMMediaManager supports audio playing and HD audio recording. Note that the audio playing and recording in NIM SDK only supports aac and amr. If you need more formats, the APP supports self-implementation, but it is not recommended.

Play

Play audio

@protocol NIMMediaManager <NSObject>
/**
 * Play an audio file
 *
 * @discussion - Start to play. The callback playAudio:didBeganWithError: under NIMMediaManagerDelegate will be triggered. After play, the callback playAudio:didCompletedWithError: under NIMMediaManagerDelegate will be triggered.
 * @param filepath - Audio file path
 */
- (void)play:(NSString *)filepath;
@end
Parameter Type Description
filepath NSString Audio file path

In which, filePath is the audio file path.

Callback of starting playing audio

@protocol NIMMediaManagerDelegate <NSObject>
/**
 * A callback for playing an audio file
 *
 * @param filePath - Audio file path
 * @param error - Error information
 */
- (void)playAudio:(NSString *)filePath didBeganWithError:(nullable NSError *)error;
@end

Callback of updating audio play progress

@protocol NIMMediaManagerDelegate <NSObject>
/**
 * A callback for updating audio playing progress
 *
 * @param filePath - Audio file path
 * @param value - Playing progress 0.0 - 1.0
 */
- (void)playAudio:(NSString *)filePath progress:(float)value;
@end

Callback of completing audio play

When the audio play is naturally completed, the following callbacks will be enabled:

@protocol NIMMediaManagerDelegate <NSObject>
/**
 * Callback that is returned after playing an audio file
 *
 * @param filePath - Audio file path
 * @param error - Error information
 */
- (void)playAudio:(NSString *)filePath didCompletedWithError:(NSError *)error
@end

Parameter List

Parameter Type Description
filepath NSString Audio file path
error NSError Error

Automatically stop audio play callback

When audio play is voluntarily stopped, the following callbacks will be enabled:

@protocol NIMMediaManagerDelegate <NSObject>
/**
 * Callback that is returned after playing an audio file
 *
 * @param filePath - Audio file path
 * @param error - Error information
 */
- (void)stopPlayAudio:(NSString *)filePath didCompletedWithError:(nullable NSError *)error;
@end

Determine if audio is playing

@protocol NIMMediaManager <NSObject>
/**
 * It determines that an audio file is being played.
 */
- (BOOL)isPlaying
@end

Switch the audio output device

@protocol NIMMediaManager <NSObject>
/**
 * Switch audio output device
 *
 * @param outputDevice - Audio output device
 *
 * @return - It determines that switchover is successful.
 */
- (BOOL)switchAudioOutputDevice:(NIMAudioOutputDevice)outputDevice
@end

NIMAudioOutputDevice list

Parameter Value Description
NIMAudioOutputDeviceReceiver 0 Receiver
NIMAudioOutputDeviceSpeaker 1 Speaker

Stop playing audio

@protocol NIMMediaManager <NSObject>
/**
 * Stop to play an audio file
 *
 */
- (void)stopPlay
@end

This action will trigger a callback of audio playing end.

Proximity monitor

@protocol NIMMediaManager <NSObject>
/**
 * It determines to automatically switch to telephone receiver mode when an audio file is played if the phone is close to ears.
 *
 */
- (void)setNeedProximityMonitor:(BOOL)needProximityMonitor;
@end

Record

Record audio

@protocol NIMMediaManager <NSObject>
/**
 * Start audio recording
 * @param type - Audio type (aac or amr)
 * @param duration - The longest recording duration.
 * @discussion - Start to record. The callback recordAudio:didBeganWithError: under NIMMediaManagerDelegate will be triggeed. After recording, the callback recordAudio:didCompletedWithError: under NIMMediaManagerDelgate will be triggered.
 */
- (void)record:(NIMAudioType)type duration:(NSTimeInterval)duration;
@end

Start recording audio callback

@protocol NIMMediaManagerDelegate <NSObject>
/**
 * A callback for starting audio recording
 *
 * @param filePath - Recorded audio file path
 * @param error - Error information
 * @discussion - If recording is failed, filePath may be nil.
 */
- (void)recordAudio:(NSString *)filePath didBeganWithError:(NSError *)error
@end

Callback after audio recording

This feature is triggered when the maximum recording time is reached, or when the recording is stopped manually.

@protocol NIMMediaManagerDelegate <NSObject>
/**
 * Callback that is returned after recording an audio file
 *
 * @param filePath - Recorded audio file path
 * @param error - Error information
 */
- (void)recordAudio:(NSString *)filePath didCompletedWithError:(NSError *)error
@end

Callback of updating audio recording progress

@protocol NIMMediaManagerDelegate <NSObject>
/**
 * A callback for updating audio recording progress
 *
 * @param currentTime - Current recording time
 */
- (void)recordAudioProgress:(NSTimeInterval)currentTime
@end

In which, currentTime is the current recording time. The time interval to trigger this callback can be set by the following property settings, and the interval is 0.3 seconds by default.

@protocol NIMMediaManager <NSObject>
/**
 * Update interval for recording progress. If the value is larger than 0, the callback recordAudioProgress will be invoked by related intervals. The value is 0.3 by default.
 */
@property (nonatomic, assign) NSTimeInterval recordProgressUpdateTimeInterval
@end

Stop recording audio

@protocol NIMMediaManager <NSObject>
/**
 * Stop audio recording
 *
 * @discussion - After stopping recording, the callback recordAudio:didCompletedWithError: under NIMMediaManagerDelegate will be triggered.
 */
- (void)stopRecord
@end

Determine if audio is being recorded

@protocol NIMMediaManager <NSObject>
/**
 * It determines that recording is being executed.
 *
 */
- (BOOL)isRecording
@end

Cancel recording

@protocol NIMMediaManager <NSObject>
/**
 * Cancel audio recording
 *
 */
- (void)cancelRecord
@end

Callback of canceling recording

@protocol NIMMediaManagerDelegate <NSObject>
/**
 * A callback for canceling a recording
 */
- (void)recordAudioDidCancelled
@end

Get record DB

  • Get peak record DB
@protocol NIMMediaManager <NSObject>
/**
 * Get peak decibel of recording
 *
 */
- (float)recordPeakPower
@end
  • Get average record DB
@protocol NIMMediaManager <NSObject>
/**
 * Get average decibel of recording
 *
 */
- (float)recordAveragePower
@end

Call interruption

  • Call interruption is triggered depending on whether the audio is being played or recorded.
@protocol NIMMediaManagerDelegate <NSObject>
/**
 * Callback that is returned when starting audio playing is interrupted
 */
- (void)playAudioInterruptionBegin

/**
 * Callback that is returned when starting recording is interrupted
 */
- (void)recordAudioInterruptionBegin
@end
  • Return to an application after the call is over
@protocol NIMMediaManagerDelegate <NSObject>
/**
 * Callback that is returned when ending audio playing is interrupted
 */
- (void)playAudioInterruptionEnd

/**
 * Callback that is returned when ending recording is interrupted
 */
- (void)recordAudioInterruptionEnd
@end

Audio-to-text

To enable the audio-to-text feature, please contact your business consultant and apply for "audio Recognition". If The API is called without enabling this feature, return 403.

Principle of audio-to-text:

  • Record audio files (maximum 60s).
  • Upload to the CommsEase storage server and return the file URL.
  • Input the URL and related parameters using the audio-to-text API, and return the converted text.
@protocol NIMMediaManager <NSObject>
/**
 * Audio-to-text
 *
 */
- (void)transAudioToText:(NIMAudioToTextOption *)option 
                  result:(NIMAudioToTextBlock)result;
@end

The properties of NIMAudioToTextOption are as follows:

Property Meaning
URL Audio URL. Currently, only the URL of the CommsEase server is supported, and external links are not supported.
filepath Local audio address
Was this topic helpful?
Yes
No
  • Receive messages
  • Receive notification messages
  • Receive multi-media messages
  • Receiving messages in a chat room
  • Message filtering
  • Broadcast message receiving
  • Audio message processing
  • Play
  • Play audio
  • Callback of starting playing audio
  • Callback of updating audio play progress
  • Callback of completing audio play
  • Automatically stop audio play callback
  • Determine if audio is playing
  • Switch the audio output device
  • Stop playing audio
  • Proximity monitor
  • Record
  • Record audio
  • Start recording audio callback
  • Callback after audio recording
  • Callback of updating audio recording progress
  • Stop recording audio
  • Determine if audio is being recorded
  • Cancel recording
  • Callback of canceling recording
  • Get record DB
  • Call interruption
  • Audio-to-text