macOS

Updated

API reference for the Agora Signaling macOS SDK for Objective-C.

This is the Objective-C API reference. For Swift, see the iOS SDK API reference.

The Signaling SDK API reference is divided into the following sections:

Setup

The API reference for the Signaling SDK documents interface descriptions, methods, basic usage, and return values of the Signaling APIs.

AgoraRtmClientConfig

Description

Use the AgoraRtmClientConfig to set additional properties for Signaling initialization. These configuration properties will take effect throughout the lifecycle of the Signaling client and affect the behavior of the Signaling client.

Method

You can create AgoraRtmClientConfig instances as follows:

__attribute__((visibility("default"))) @interface AgoraRtmClientConfig: NSObject

- (instancetype _Nullable)init NS_UNAVAILABLE;

- (instancetype _Nonnull) initWithAppId:(NSString * _Nonnull)appId
                                 userId:(NSString * _Nonnull)userId;

@property (nonatomic, assign) AgoraRtmAreaCode areaCode;
@property (nonatomic, assign)  AgoraRtmProtocolType protocolType;
@property (nonatomic, assign) unsigned int presenceTimeout;
@property (nonatomic, assign) unsigned int heartbeatInterval;
@property (nonatomic, assign) unsigned int reconnectTimeout;
@property (nonatomic, copy, nonnull) NSString *appId;
@property (nonatomic, copy, nonnull) NSString *userId;
@property (nonatomic, assign) BOOL useStringUserId;
@property (nonatomic, assign) BOOL multipath;
@property (nonatomic, assign) BOOL ispPolicyEnabled;
@property (nonatomic, copy, nullable) AgoraRtmLogConfig * logConfig;
@property (nonatomic, copy, nullable) AgoraRtmProxyConfig * proxyConfig;
@property (nonatomic, copy, nullable) AgoraRtmEncryptionConfig * encryptionConfig;
@property (nonatomic, copy, nullable) AgoraRtmPrivateConfig * privateConfig;
@end
MethodsDescription
initPrevents users from initializing the AgoraRtmClientConfig instance without providing the required parameters.
initWithAppIdRequires users to provide the appId and userId parameters during initializing the AgoraRtmClientConfig instance.
PropertiesTypeRequiredDefaultDescription
appIdNSStringRequired-App ID obtained when creating a project in the Agora Console.
userIdNSStringRequired-User ID for identify a user or a device. To distinguish each user or device, you need to ensure that the userId parameter is globally unique and remains unchanged throughout the user or device's lifecycle.
areaCodeAgoraRtmAreaCodeOptionalAgoraRtmAreaCodeGLOBService area code, you can choose according to the region where your business is deployed. See AgoraRtmAreaCode.
protocolTypeAgoraRtmProtocolTypeOptionalAgoraRtmProtocolTypeTcpUdpProtocol types for message transmission. Signaling by default utilizes one-way TCP and one-way UDP protocols for transmission, but you have the flexibility to modify the protocol types based on your requirements. See AgoraRtmProtocolType.
presenceTimeoutunsigned intOptional300Presence timeout in seconds, and the value range is [5,300]. This parameter refers the delay imposed by the Signaling server before sending a AgoraRtmPresenceEventTypeRemoteConnectionTimeout event notification to other users once it determines that a client has timed out. If the client reconnects and returns to the channel within the specified time, the Signaling server does not send the AgoraRtmPresenceEventTypeRemoteConnectionTimeout event notification to other participants or delete the temporary user data associated with the user.
heartbeatIntervalunsigned intOptional5Heartbeat interval in seconds, and the value range is [5,1800]. This parameter refers to the time interval at which the client sends heartbeat packets to the Signaling server. If the client fails to send heartbeat packets to the Signaling server within the specified time, the Signaling server determines that the client has timed out. Please note that this parameter affects the PCU count, which in turn affects billing.
reconnectTimeoutuint32_tOptional0SDK connection timeout in seconds. The value range is [15,3600]. The default value is 0 which means no timeout; the SDK keeps retrying until successful. This parameter applies to both the initial login to the Signaling service and reconnection after disconnection:
- If the initial login times out, the SDK triggers the completion callback with errorInfo as AgoraRtmErrorLoginTimeout, and also triggers the didReceiveLinkStateEvent callback with currentState as AgoraRtmLinkStateFailed and reasonCode as AgoraRtmLinkStateChangeReasonLoginTimeout.
- If reconnection times out, the SDK triggers the didReceiveLinkStateEvent callback with currentState as AgoraRtmLinkStateFailed and reasonCode as AgoraRtmLinkStateChangeReasonReconnectTimeout.
useStringUserIdBOOLOptionaltrueWhether to use string-type user IDs:
- true: Use string-type user IDs.
- false: Use number-type user IDs. The SDK automatically converts string-type user IDs to number-type ones. ones. In this case, the userId parameter must be a numeric string (for example, "123456"), otherwise initialization fails.When using Agora RTC and Signaling products at the same time, it is necessary to ensure that the userId parameter is consistent.
ispPolicyEnabledBoolOptionalfalseWhether to enable the ISP domain policy restriction. In IoT scenarios, devices may be restricted by Internet Service Providers (ISPs). Use this field to set the SDK's connection mode to connect to servers with domains registered with the operator or those in the IP whitelist:
- true: Enable the ISP domain policy restriction. This setting applies to scenarios where IoT devices use IoT SIM cards for network access. The SDK will only connect to servers with domains registered with the operator or those in the IP whitelist.
- false: (Default) Disable the ISP domain policy restriction. This setting applies to most common scenarios.
logConfigAgoraRtmLogConfigOptional-Log configuration properties such as the log storage size, storage path, and level.
proxyConfigAgoraRtmProxyConfigOptional-When using the Proxy feature of Signaling, you need to configure this parameter.
encryptionConfigAgoraRtmEncryptionConfigOptional-When using the client-side encryption feature of Signaling, you need to configure this parameter.
privateConfigAgoraRtmPrivateConfigOptional-When using the private deployment feature of Signaling, you need to configure this parameter.
AgoraRtmLogConfig

Use the AgoraRtmLogConfig instance to configure and store local log files named agora.log. During the debugging phase, you can greatly improve efficiency by storing and tracking the running status of the app through logs. If you encounter complex problems and need Agora technical support to assist with the investigation, you need to provide the log information. AgoraRtmLogConfig contains the following properties:

PropertiesTypeRequiredDefaultDescription
filePathNSStringOptional-Log file storage paths.
fileSizeInKBintOptional1024Log file size in KB, with a value range of [128,1024].
- If the value you enter is less than 128, the SDK sets the value to 128.
- If the value you enter is greater than 1024, the SDK sets the value to 1024.
levelAgoraRtmLogLevelOptionalAgoraRtmLogLevelInfoOutput level of log information. See AgoraRtmLogLevel.
AgoraRtmProxyConfig

Use the AgoraRtmProxyConfig instance to set properties related to the client Proxy service. In some restricted network environments, you might need to use this feature.

Caution

You need to keep your Proxy username and password safe. The Signaling SDK does not parse, store, or forward your username and password in any way. In addition, if you modify the Proxy settings during the app running process, the settings will take effect only after restarting the Signaling client.

AgoraRtmProxyConfig contains the following properties:

MethodsDescription
initPrevents users from initializing the AgoraRtmProxyConfig instance without providing the required parameters.
initWithServerRequires users to provide the server, port, and proxyType parameters during initializing the AgoraRtmProxyConfig instance.
PropertiesTypeRequiredDefaultDescription
proxyTypeAgoraRtmProxyTypeOptionalAgoraRtmProxyTypeNoneProxy protocol type. See AgoraRtmProxyType.
serverNSStringRequired-Proxy server domain name or IP address.
portunsigned shortOptional-Proxy listening port.
accountNSStringOptional-Proxy login account.
passwordNSStringOptional-Proxy login password.
AgoraRtmEncryptionConfig

Use the AgoraRtmEncryptionConfig instance to set the properties required for the client-side encryption. After successfully setting encryption modes, encryption keys, and other related properties, the SDK automatically encrypts and decrypts all messages sent or all statuses set by the user on the client side.

Caution

Once you set the encryption feature, all users must use the same encryption mode and key, otherwise users cannot communicate with each other.

AgoraRtmEncryptionConfig contains the following properties:

PropertiesTypeRequiredDefaultDescription
encryptionModeAgoraRtmEncryptionModeOptionalAgoraRtmEncryptionNoneEncryption mode. See AgoraRtmEncryptionMode.
encryptionKeyNSStringOptional-User-defined encryption key, unlimited length. Agora recommends using a 32-byte key.
encryptionKdfSaltNSDataOptional-User-defined encryption salt, length is 32 bytes. Agora recommends using OpenSSL to generate salt on the server side.
AgoraRtmPrivateConfig

Use the AgoraRtmPrivateConfig instance to set the properties required for the private deployment. AgoraRtmPrivateConfig contains the following properties:

PropertiesTypeRequiredDefaultDescription
serviceTypeEnumSet<RtmServiceType>Optional-Service type. See AgoraRtmServiceType.
accessPointHostsNSArray<NSString *>Optional-An array of server addresses, where you can fill in domain names or IP addresses.

Basic usage

AgoraRtmClientConfig* rtm_config = [[AgoraRtmClientConfig alloc] initWithAppId:@"your_appid" userId:@"your_userid"];

AgoraRtmEncryptionConfig* encryptionConfig = [[AgoraRtmEncryptionConfig alloc] init];
encryptionConfig.encryptionKey = @"you_encryption_key";
encryptionConfig.encryptionMode = AgoraRtmEncryptionAES256GCM;
unsigned char bytes[32] = ;
encryptionConfig.encryptionSalt = [NSData dataWithBytes:bytes length:32];

AgoraRtmLogConfig* log_config = [[AgoraRtmLogConfig alloc] init];
log_config.level= AgoraRtmLogLevelError;
log_config.filePath= @"your_path";
log_config.fileSizeInKB = 512;

AgoraRtmProxyConfig* proxy_config = [[AgoraRtmProxyConfig alloc] initWithServer:@"your_proxy_server" port:8080 proxyType:AgoraRtmProxyTypeHttp];
proxy_config.account = @"username";
proxy_config.password = @"password";

AgoraRtmPrivateConfig* private_config = [[AgoraRtmPrivateConfig alloc] init];
private_config.accessPointHosts = @[@"your_private_server"];
private_config.serviceType = AgoraRtmServiceTypeStream | AgoraRtmServiceTypeMessage;

rtm_config.privateConfig = private_config;
rtm_config.proxyConfig = proxy_config;
rtm_config.logConfig = log_config;
rtm_config.encryptionConfig = encryptionConfig;
rtm_config.useStringUserId = true;
rtm_config.heartbeatInterval = 5;
rtm_config.protocolType = AgoraRtmProtocolTypeTcpUdp;
rtm_config.areaCode = AgoraRtmAreaCodeGLOB;
rtm_config.presenceTimeout = 300;

Create an instance

Description

Call the initWithConfig method to create and initialize the Signaling Client instance.

Information


- You need to create and initialize a client instance before calling other Signaling APIs.
- To distinguish each user or device, you need to ensure that the userId parameter is globally unique and remains unchanged throughout the user or device's lifecycle.

Method

You can create and initialize an instance as follows:

- (instancetype _Nullable) initWithConfig: (AgoraRtmClientConfig * _Nonnull)config
                                 delegate: (id <AgoraRtmClientDelegate> _Nullable)delegate;
                                    error: (NSError**)error NS_SWIFT_NAME(init(_:delegate:));
ParametersTypeRequiredDefaultDescription
configAgoraRtmClientConfigRequired-Initialize the configuration parameters of the Signaling Client. See AgoraRtmClientConfig.
delegateid &lt;AgoraRtmClientDelegate&gt;Optional-Signaling event notification listener settings. See Event listeners.
errorNSErrorRequired-(Output) Error description.

Basic usage

AgoraRtmClientConfig* rtm_cfg = [[AgoraRtmClientConfig alloc] initWithAppId:@"your_appid" userId:@"your_userid"];
NSError* initError = nil;
AgoraRtmClientKit* rtm = [[AgoraRtmClientKit alloc] initWithConfig:rtm_cfg delegate:handler error:&initError];

Return Value

  • Success: Creates a Signaling client instance for subsequent calls to other Signaling APIs.
  • Failure: nil.

Event Listeners

DescriptionAgoraRtmClientDelegate

Signaling event notifications.

Signaling has a total of 8 types of event notifications, as shown in the following table:

Event TypeDescription
didReceiveMessageEventReceive message notifications from all subscribed Message Channels or topic message notifications subscribed to, in all Stream Channels you join. See AgoraRtmMessageEvent .
didReceivePresenceEventReceive presence event notifications in subscribed message channels and joined stream channels. See AgoraRtmPresenceEvent
didReceiveTopicEventReceive all topic event notifications in joined stream channels. See AgoraRtmTopicEvent
didReceiveStorageEventReceive channel metadata event notifications in subscribed message channels and joined stream channels, and the user metadata event notification of the subscribed users. See AgoraRtmStorageEvent
didReceiveLockEventReceive lock event notifications in subscribed message channels and joined stream channels. See AgoraRtmLockEvent
connectionChangedToState(Deprecated) Receive event notifications when client connection status changes. For details, see AgoraRtmClientConnectionState and AgoraRtmClientConnectionChangeReason.
didReceiveLinkStateEventReceive event notifications when client connection status changes. See AgoraRtmLinkStateEvent.
tokenPrivilegeWillExpireReceive event notifications when the client tokens are about to expire.

Add event listeners

You can add an event listener object through the following ways:

  • Add only an event listener object during initialization.
  • Add one or more event listener objects at any point during the app's lifecycle by calling the addDelegate method.
Adding During Initialization

When initializing the Signaling client instance using the initWithConfig method, you can refer to the following example code to add an event listener object:

@interface RtmListener : NSObject <AgoraRtmClientDelegate>

@end

@implementation RtmListener

 // triggered when received message from remote
-(void) rtmKit:(AgoraRtmClientKit *)rtmKit didReceiveMessageEvent:(AgoraRtmMessageEvent *)event {}

 // triggered when channel lock info changed
-(void) rtmKit:(AgoraRtmClientKit *)rtmKit didReceiveLockEvent:(AgoraRtmLockEvent *)event {}

 // triggered when prensence info changed
-(void) rtmKit:(AgoraRtmClientKit *)rtmKit didReceivePresenceEvent:(AgoraRtmPresenceEvent *)event {}

 // triggered when subscribed strorage changed
-(void) rtmKit:(AgoraRtmClientKit *)rtmKit didReceiveStorageEvent:(AgoraRtmStorageEvent *)event {}

 // triggered when token will expire
-(void) rtmKit:(AgoraRtmClientKit *)rtmKit tokenPrivilegeWillExpire:(NSString *)channel {}

 // triggered when connection state changed
-(void) rtmKit:(AgoraRtmClientKit *)kit channel:(NSString *)channelName connectionChangedToState:(AgoraRtmClientConnectionState)state reason:(AgoraRtmClientConnectionChangeReason)reason {}

 // triggered when link state changed
- (void)rtmKit:(AgoraRtmClientKit *)rtmKit didReceiveLinkStateEvent:(AgoraRtmLinkStateEvent *)event {}
@end

AgoraRtmClientConfig* rtm_cfg = [[AgoraRtmClientConfig alloc] initWithAppId:@"your_appid" userId:@"your_userid"];

 // add event listener
RtmListener* handler =  [[RtmListener alloc] init];
NSError* initError = nil;
AgoraRtmClientKit* rtm = [[AgoraRtmClientKit alloc] initWithConfig:rtm_cfg delegate:handler error:&initError];
Adding at Any Time

addDelegate At any point during the app's lifecycle, if you need to add multiple event listener objects, you can call the addDelegate method multiple times.

@interface RtmListenerEx : NSObject <AgoraRtmClientDelegate>
 // your listener code
@end

@implementation RtmListenerEx
 // your listener code
@end
RtmListenerEx* handlerEx =  [[RtmListenerEx alloc] init];

[rtm addDelegate:handlerEx];

removeDelegate If you no longer need to listen to a specific event listener object, but still need to listen to other event listener objects, you can call the removeDelegate method to remove the specified event listener object.

[rtm removeDelegate:handlerEx];
AgoraRtmMessageEvent

Message event.

AgoraRtmMessageEvent contains the following properties:

PropertiesTypeDescription
channelTypeAgoraRtmChannelTypeChannel types. See AgoraRtmChannelType.
channelNameNSStringChannel name.
channelTopicNSStringTopic name.
messageAgoraRtmMessageMessage.
publisherNSStringUser ID of the message publisher.
customTypeNSStringA user-defined field. Only supports NSString type.
timestampunsigned long longThe timestamp when the event occurs.

AgoraRtmMessage contains the following properties:

PropertiesTypeDescription
rawDataNSDataBinary message.
stringDataNSStringString message.
AgoraRtmPresenceEvent

User presence event.

AgoraRtmPresenceEvent contains the following properties:

PropertiesTypeDescription
typeAgoraRtmPresenceEventTypePresence event type. See AgoraRtmPresenceEventType.
channelTypeAgoraRtmChannelTypeChannel types. See AgoraRtmChannelType.
channelNameNSStringChannel name.
publisherNSStringUser ID of the message publisher.
statesNSDictionaryKey-value pair that identifies the user's presence state.
intervalAgoraRtmPresenceIntervalInfoIn the Interval state, the aggregated incremental information of event notifications such as user joining, leaving, timeout, and status change in the previous period of the current channel.
snapshotNSArray&lt;AgoraRtmUserState *&gt;When the user first joins the channel, the server pushes the snapshot data of all users in the current channel and their statuses to the user.
timestampunsigned long longThe timestamp when the event occurs.

The AgoraRtmPresenceIntervalInfo data type contains the following properties:

PropertiesTypeDescription
joinUserListNSArray&lt;NSString *&gt;List of users who joined the channel in the previous cycle.
leaveUserListNSArray&lt;NSString *&gt;List of users who left the channel in the previous cycle.
timeoutUserListNSArray&lt;NSString *&gt;List of users who timed out joining the channel in the previous cycle.
userStateListArrayList&lt;UserState&gt;List of users whose status has changed in the previous cycle. Contains user ID and status key-value pairs.

The AgoraRtmUserState data type contains the following properties:

PropertiesTypeDescription
userIdNSStringUser ID.
statesNSDictionaryList of online users and their temporary state information in a specified channel.

AgoraRtmStateItem data type contains the following properties:

PropertiesTypeDescription
keyNSStringKey of the user state. If the specified key already exists, the SDK overwrites the value; if the specified key does not exist, the SDK creates the key-value pair.
valueNSStringValue of the user state.
AgoraRtmTopicEvent

Topic event.

AgoraRtmTopicEvent contains the following properties:

PropertiesTypeDescription
typeAgoraRtmTopicEventTypeTopic event type. See AgoraRtmTopicEventType.
channelNameNSStringChannel name.
publisherNSStringUser ID.
topicInfosNSArray&lt;AgoraRtmTopicInfo *&gt;Topic information.
timestampunsigned long longThe timestamp when the event occurs.

The AgoraRtmTopicInfo data type contains the following properties:

PropertiesTypeDescription
topicNSStringTopic name.
publishersNSArray&lt;AgoraRtmPublisherInfo *&gt;Message publisher array.

The AgoraRtmPublisherInfo data type contains the following properties:

PropertiesTypeDescription
publisherUserIdNSStringUser ID of the message publisher.
publisherMetaNSStringMetadata of the message publisher.
AgoraRtmStorageEvent

Storage event.

AgoraRtmStorageEvent contains the following properties:

PropertiesTypeDescription
channelTypeAgoraRtmChannelTypeChannel types. See AgoraRtmChannelType.
storageTypeAgoraRtmStorageTypeStorage type. See AgoraRtmStorageType.
eventTypeAgoraRtmStorageEventTypeStorage event type. See AgoraRtmStorageEventType.
targetNSStringUser ID or channel name.
dataAgoraRtmMetadataMetadata item. See AgoraRtmMetadata.
timestampunsigned long longThe timestamp when the event occurs.
AgoraRtmLockEvent

Lock event.

AgoraRtmLockEvent contains the following properties:

PropertiesTypeDescription
channelTypeAgoraRtmChannelTypeChannel types. See AgoraRtmChannelType.
eventTypeAgoraRtmLockEventTypeLock event type. See AgoraRtmLockEventType.
channelNameNSStringChannel name.
lockDetailListArrayList&lt;LockDetail&gt;Details of lock.
timestampunsigned long longThe timestamp when the event occurs.

The AgoraRtmLockDetail data type contains the following properties:

PropertiesTypeDescription
lockNameNSStringLock name.
ownerNSStringThe ID of the user who has a lock.
ttlintThe expiration time of the lock. The value is in seconds, ranging from [10 to 300]. When the user who owns the lock goes offline, if the user returns to the channel within the time they can still use the lock; otherwise, the lock is released and the users who listen for the didReceiveLockEvent event receives the AgoraRtmLockEventTypeLockReleased event.
AgoraRtmLinkStateEvent

SDK link state event. AgoraRtmLinkStateEvent data type contains the following properties:

ParametersTypeDescription
currentStateAgoraRtmLinkStateThe current link state. See AgoraRtmLinkState.
previousStateAgoraRtmLinkStateThe previous link state. See AgoraRtmLinkState.
serviceTypeAgoraRtmServiceTypeThe network connection type. See AgoraRtmServiceType.
operationAgoraRtmLinkOperationThe operation that triggered the current state transition. See AgoraRtmLinkOperation.
reasonCodeAgoraRtmLinkStateChangeReasonThe reason for this state transition. See AgoraRtmLinkStateChangeReason.
reasonNSStringThe reason for the current state transition. This parameter will be deprecated in the future, please use the reasonCode parameter instead.
affectedChannelsNSArray&lt;NSString *&gt;The channels affected by the current state transition.
unrestoredChannelsNSArray&lt;NSString *&gt;The information about the channels to which subscription or joining has not been restored, including the channel name, channel type, and temporary state data in the channel. Typically, this information is empty.
isResumedBOOLWithin 2 minutes of the disconnection, whether the state transitions from AgoraRtmLinkStateDisconnected to AgoraRtmLinkStateConnected. true refers to the state has transitioned.
timestampunsigned long longThe timestamp when the event occurs.

AgoraRtmClientKit

Signaling client instance

loginByToken

Description

After creating and initializing the Signaling instance, you need to perform the loginByToken operation to log in to the Signaling service. After successful login, the client establishes a long connection with the Signaling server, and then the SDK allows the client to access Signaling resources.

Information

After the user successfully logs in to the Signaling service, the PCU of the application increases, which affects your billing data.

Method

You can log in to the Signaling system as follows:

- (void) loginByToken: (NSString* _Nullable)token
           completion: (AgoraRtmOperationBlock _Nullable)completionBlock;
ParametersTypeRequiredDefaultDescription
tokenNSStringOptional-The token used for logging in to Signaling.
- If you have enabled token authentication for your project, use either the Signaling temporary token or obtain a Signaling token generated by your token server.
- If your project does not enable token authentication, use an empty string or the App ID of a project that has Signaling services enabled.
completionBlockAgoraRtmOperationBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmCommonResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

After calling most of the APIs of the Signaling Objective-C SDK, the SDK executes a completionBlock callback, which includes response and errorInfo parameters. Based on different calling results, the SDK returns different parameter values:

  • Success: Returns the corresponding data in the response parameter, and the nil in the errorInfo parameter.
  • Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

The \errorInfo` of AgoraRtmErrorInfo` data type contains the error code, error reason, and API operation name for this call, as shown in the following table:

PropertiesTypeDescription
errorCodeAgoraRtmErrorCodeError code for this operation.
reasonNSStringError reason for this operation.
operationNSStringOperation type.

To find out the cause of the error and get the corresponding solution, use the errorCode field with the error codes table.

Basic usage

[rtm loginByToken:@"token" completion:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"login success!!");
    } else {
        NSLog(@"login failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

logout

Description

When you no longer need to operate, you can log out of the system. This operation affects the PCU item in your billing data.

Method

You can log out as follows:

- (void) logout: (AgoraRtmOperationBlock _Nullable)completionBlock;
ParametersTypeRequiredDefaultDescription
completionBlockAgoraRtmOperationBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmCommonResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

Basic usage

[rtm logout:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"logout success!!");
    } else {
        NSLog(@"logout failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

releaseLock

Description

Once you no longer need the Signaling service, it is best to destroy the AgoraRtmClientKit instance. Doing so protects you from the performance degradation caused by memory leaks, errors, and exceptions.

Method

You can destroy the AgoraRtmClientKit instance as follows:

- (AgoraRtmErrorCode) destroy;

Basic usage

[rtm destroy];

Return Value

The releaseLock method returns an AgoraRtmErrorCode data structure. See Error code.

User authentication

Authentication is the process of validating the identity of each user before they access a system. Agora uses digital tokens to authenticate users and their privileges.

Signaling provides 3 types of channels: message channels, user channels and stream channels. Different types of channels require different types of tokens:

  • For message channels and user channels: When logging in to the Signaling system using the loginByToken method, you only need to pass the token that enables Signaling service.
  • For stream channels: In addition to the Signaling token, when joining a stream channel using the joinTopic method, you also need to pass the token that enables RTC service.

The token is valid for up to 24 hours. Agora recommends that you update the token before it expires. This article describes how to update the token.

For more information on generating and using tokens, see Secure authentication with tokens.

AgoraRtmClientKit.renewToken

Description

Call the AgoraRtmClientKit.renewToken method to renew the Signaling token.

To ensure timely token updates, Agora recommends listening for the tokenPrivilegeWillExpire callback. See Event listeners for details. Once you successfully add the event listener, when the Signaling token is about to expire within 30 seconds, the SDK triggers the tokenPrivilegeWillExpire callback to notify the user about the impending token expiration.

Upon receiving this callback, you can generate a new Signaling token on the server-side and call the renewToken method to provide the SDK with the newly generated Signaling token.

Method

You can call the AgoraRtmClientKit.renewToken method as follows:

- (void) renewToken:(NSString* _Nonnull)token
         completion:(AgoraRtmOperationBlock _Nullable)completionBlock NS_SWIFT_NAME(renewToken(_:completion:));
ParametersTypeRequiredDefaultDescription
tokenstringRequired-The newly generated Signaling token.
completionBlockAgoraRtmOperationBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmCommonResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

Basic usage

[rtm renewToken:@"new token" completion:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"renew token success!!");
    } else {
        NSLog(@"renew token failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

AgoraRtmStreamChannel.renewToken

Description

Call the AgoraRtmStreamChannel.renewToken method to renew the RTC token.

To ensure timely token updates, Agora recommends listening for the tokenPrivilegeWillExpire callback. See Event listeners for details. Once you successfully add the event listener, when the RTC token is about to expire within 30 seconds, the SDK triggers the tokenPrivilegeWillExpire callback to notify the user about the impending token expiration.

Upon receiving this callback, you can generate a new RTC token on the server-side and call the renewToken method to provide the SDK with the newly generated RTC token.

Method

You can call the AgoraRtmStreamChannel.renewToken method as follows:

- (void)renewToken:(NSString* _Nonnull)token
        completion:(AgoraRtmOperationBlock _Nullable)completionBlock NS_SWIFT_NAME(renewToken(_:completion:));
ParametersTypeRequiredDefaultDescription
tokenstringRequired-The newly generated RTC token.
completionBlockAgoraRtmOperationBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmCommonResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

Basic usage

[streamChannel renewToken:@"new token" completion:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"renew token success!!");
    } else {
        NSLog(@"renew token failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

Channels

Signaling provides a highly efficient channel management mechanism for data transmission. Any user who subscribes or joins a channel can receive messages and events transmitted within 100 milliseconds. Signaling allows clients to subscribe to hundreds or even thousands of channels. Most Signaling APIs perform actions such as sending, receiving, and encrypting based on channels.

Based on capabilities of Agora, Signaling channels are divided into two types to match different application use-cases:

  • Message Channel: Follows the industry-standard Pub/Sub (publish/subscribe) mode. You can send and receive messages within the channel by subscribing to a channel, and do not need to create the channel in advance. There is no limit to the number of publishers and subscribers in a channel.

  • User Channel: Point-to-point message sending and receiving based on the Pub/Sub (publish/subscribe) model. Users do not need to subscribe to the channel, they can directly specify the user ID to send messages. To receive messages, they only need to listen to didReceiveMessageEvent events.

  • Stream Channel: Follows a concept similar to the observer pattern in the industry, where users need to create and join a channel before sending and receiving messages. You can create different topics in the channel, and messages are organized and managed through topics.

AgoraRtmClientKit Signaling client instance

subscribeTopic

Description

Signaling provides event notification capabilities for messages and states. By listening for callbacks, you can receive messages and events within subscribed channels. For information on how to add and set event listeners, see Event Listeners.

By calling the subscribeTopic method, the client can subscribe to a message channel and start receiving messages and event notifications within the channel. After successfully calling this method, users who subscribe to the channel and enable the presence event listener can receive a AgoraRtmPresenceEventTypeRemoteJoinChannel type of the didReceivePresenceEvent event. See Event Listeners.

Information

This method only applies to the message channel.

Method

You can call the subscribeTopic method as follows:

- (void)subscribeWithChannel:(NSString * _Nonnull)channelName
                      option:(AgoraRtmSubscribeOptions * _Nullable)subscribeOption
                  completion:(AgoraRtmOperationBlock _Nullable)completionBlock;
ParametersTypeRequiredDefaultDescription
channelNameNSStringRequired-Channel name.
subscribeOptionAgoraRtmSubscribeOptionsOptional-Options for subscribing to a channel.
completionBlockAgoraRtmOperationBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmCommonResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

AgoraRtmSubscribeOptions contains the following properties:

PropertiesTypeRequiredDefaultDescription
featuresAgoraRtmSubscribeChannelFeatureOptionalAgoraRtmSubscribeChannelFeatureMessage and AgoraRtmSubscribeChannelFeaturePresenceSets event notification types when subscribing to a channel. You can use bitwise operations to set multiple event notifications simultaneously. The SDK enables the message and presence event notifications by default.

Basic usage

AgoraRtmSubscribeOptions* opt = [[AgoraRtmSubscribeOptions alloc] init];
opt.features = AgoraRtmSubscribeChannelFeatureMessage|AgoraRtmSubscribeChannelFeaturePresence;
[rtm subscribeWithChannel:@"you_channel" option:opt completion:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"subscribe success!!");
    } else {
        NSLog(@"subscribe failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

unsubscribeTopic

Description

If you no longer need to subscribe to a channel, you can call the unsubscribeTopic method to unsubscribe from the channel. After successfully calling this method, users who subscribe to the channel and enable event listeners can receive the AgoraRtmPresenceEventTypeRemoteLeaveChannel type of the didReceivePresenceEvent event notification. See Event Listeners.

Information

This method only applies to the message channel.

Method

You can call the unsubscribeTopic method as follows:

- (void) unsubscribeWithChannel: (NSString* _Nonnull)channelName
                     completion: (AgoraRtmOperationBlock _Nullable)completionBlock;
ParametersTypeRequiredDefaultDescription
channelNameNSStringRequired-Channel name.
completionBlockAgoraRtmOperationBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmCommonResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

Basic usage

[rtm unsubscribeWithChannel:@"you_channel" option:opt completion:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"subscribe success!!");
    } else {
        NSLog(@"subscribe failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

initWithConfig

Description

Before using a stream channel, you need to call the initWithConfig method to create the AgoraRtmStreamChannel instance. After successfully creating the instance, you can call its relevant methods to implement functions, such as joining the channel, leaving the channel, sending messages in a topic, and subscribing to messages in a topic.

Information

This method only applies to the stream channel.

Method

You can call the initWithConfig method as follows:

- (AgoraRtmStreamChannel * _Nullable)createStreamChannel:(NSString * _Nonnull)channelName
                                                   error:(NSError**)error NS_SWIFT_NAME(createStreamChannel(_:));
ParametersTypeRequiredDefaultDescription
channelNameNSStringRequired-Channel name.
errorNSErrorRequired-(Output) Error description.

Basic usage

AgoraRtmStreamChannel* stream_channel = [rtm createStreamChannel:@"your_channel"];
    if (stream_channel == nil) {
        NSLog("create stream channel failed");
    } else {
        NSLog("create stream channel success");
    };

Return Value

  • Success: Returns an instance of AgoraRtmStreamChannel to use for subsequent calls to other stream channel APIs.
  • Failure: nil.

AgoraRtmStreamChannel Stream channel instance

joinTopic

Description

After successfully creating a stream channel, you can call the joinTopic method to join the stream channel. Once you join the channel, you can implement channel-related functions. At this point, users who subscribe to the channel and add event listeners can receive the following event notifications:

  • For the local user:
    • The AgoraRtmPresenceEventTypeSnapshot type of the didReceivePresenceEvent event.
    • The AgoraRtmTopicEventTypeSnapshot type of the didReceiveTopicEvent event.
  • For remote users: The AgoraRtmPresenceEventTypeRemoteJoinChannel type of the didReceivePresenceEvent event.

Information

This method only applies to the stream channel.

Method

You can call the joinTopic method as follows:

- (void)joinWithOption: (AgoraRtmJoinChannelOption * _Nonnull)option
            completion: (AgoraRtmOperationBlock _Nullable)completionBlock;
ParametersTypeRequiredDefaultDescription
optionAgoraRtmJoinChannelOptionRequired-Options for joining a channel.
completionBlockAgoraRtmOperationBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmCommonResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

The AgoraRtmJoinChannelOption data type contains the following properties:

PropertiesTypeRequiredDefaultDescription
tokenNSStringOptional-An RTC token for joining a stream channel.
- If you have enabled token authentication for your project, generate a temporary RTC token or obtain an RTC token generated by your token server.
- If you have not enabled token authentication for your project, use an empty string or the App ID of your project that has RTC and Signaling services enabled.
featuresAgoraRtmJoinChannelFeatureOptionalAgoraRtmJoinChannelFeaturePresenceSets event notification types when joining a channel. You can use bitwise operations to set multiple event notifications simultaneously. The SDK enables the presence event notification by default.

Basic usage

AgoraRtmJoinChannelOption* join_opt =  [[AgoraRtmJoinChannelOption alloc] init];
join_opt.token =  @"your_token";
join_opt.features = AgoraRtmSubscribeChannelFeaturePresence | AgoraRtmSubscribeChannelFeatureMetadata;

[stream_channel joinWithOption:join_opt completion:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"join channel success!!");
    } else {
        NSLog(@"join channel failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

leaveTopic

Description

If you no longer need to stay in a channel, you can call the leaveTopic method to leave the channel. After leaving the channel, you can no longer receive any messages, states, or event notifications from this channel. At the same time, you can no loger be the topic publisher or subscriber of all topics. If you want to restore your previous publisher role and subscribing relationship, you need to call joinTopic, joinTopic and subscribeTopic methods in order.

After successfully leaving the channel, remote users in the channel can receive the AgoraRtmPresenceEventTypeRemoteLeaveChannel type of the didReceivePresenceEvent event notification. For details, see Event Listeners.

Information

This method only applies to the stream channel.

Method

You can call the leaveTopic method as follows:

- (void)leave: (AgoraRtmOperationBlock _Nullable)completionBlock;
ParametersTypeRequiredDefaultDescription
completionBlockAgoraRtmOperationBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmCommonResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

Basic usage

[stream_channel leave:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"leave channel success!!");
    } else {
        NSLog(@"leave channel failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

releaseLock

Description

If you no longer need a channel, you can call the releaseLock method to destroy the corresponding stream channel instance and release resources. Calling the releaseLock method does not destroy the stream channel, and it can be re-joined later by calling initWithConfig and joinTopic again.

Caution

This method only applies to the stream channel. If you don't call leaveTopic to leave the channel before directly calling releaseLock to destroy the stream channel instance, the SDK automatically calls the leaveTopic and triggers the corresponding event.

Method

You can call the releaseLock method as follows:

- (AgoraRtmErrorCode) destroy;

Basic usage

[stream_channel destroy];
stream_channel = nil;

Return Value

The releaseLock method returns an AgoraRtmErrorCode data structure. See Error code.

Topics

Topic is a data stream management mechanism in stream channels. Users can use topics to subscribe to and distribute data streams, as well as notify events in data streams in stream channels.

Information

Topics only exist in stream channels. Therefore, before using relevant features, you need to create the AgoraRtmStreamChannel instance.

AgoraRtmStreamChannel Stream channel instance

joinTopic

Description

The purpose of joining a topic is to register as one of the message publishers for the topic, so that the user can send messages in the topic. This operation does not affect whether or not the user becomes a subscriber to the topic.

Information

  • Currently, Signaling supports a single client joining up to 8 topics in the same stream channel at a time.
  • Before joining a topic, a user needs to create the AgoraRtmStreamChannel instance and call the joinTopic method to join the channel.

After successfully joining a topic, users who subscribe to that topic and add event listeners can receive the AgoraRtmTopicEventTypeRemoteJoinTopic type of the didReceiveTopicEvent event notification. For details, see Event Listeners.

Method

You can call the joinTopic method as follows:

- (void) joinTopic:(NSString * _Nonnull)topic
            option:(AgoraRtmJoinTopicOption * _Nullable)option
        completion:(AgoraRtmOperationBlock _Nullable)completionBlock
ParametersTypeRequiredDefaultDescription
topicNSStringRequired-Topic name.
optionAgoraRtmJoinTopicOptionOptional-Options for joining a topic.
completionBlockAgoraRtmOperationBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmCommonResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

The AgoraRtmJoinTopicOption data type contains the following properties:

PropertiesTypeRequiredDefaultDescription
qosAgoraRtmMessageQosOptionalAgoraRtmMessageQosUnorderedWhether the data transmitted in the topic is ordered. See AgoraRtmMessageQos.
priorityAgoraRtmMessagePriorityOptionalAgoraRtmMessagePriorityNormalThe priority of data transmission in the topic compared to other topics in the same channel. See AgoraRtmMessagePriority.
metaNSStringOptional-Adds additional metadata when joining the topic.
syncWithMediaBOOLOptionalfalseWhether the data sent in this topic is synchronized (timestamp-aligned) with the RTC audio and video data stream of the common channel.

Basic usage

AgoraRtmJoinTopicOption* join_topic_opt = [[AgoraRtmJoinTopicOption alloc] init];
join_topic_opt.qos = AgoraRtmMessageQosOrdered;
[stream_channel joinTopic:@"your_topic" option:join_topic_opt completion:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"join topic success!!");
    } else {
        NSLog(@"join topic failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

publishTopicMessage

Description

Use the publishTopicMessage method to send messages to a topic. Users who have subscribed to the topic and the message publisher in the channel can receive the message within 100 milliseconds. Before calling the publishTopicMessage method, users need to join the stream channel, and then register as a message publisher for that topic by calling the joinTopic method.

The messages sent by users are encrypted with TLS during transmission, and data link encryption is enabled by default and cannot be disabled. To achieve a higher level of data security, users can also enable client encryption during initialization. For details, see Setup.

Method

You can call the publishTopicMessage[1/2] and publishTopicMessage[2/2] method as follows:

 // publishTopicMessage[1/2]
- (void) publishTopicMessage:(NSString * _Nonnull)topic
                     message:(NSString * _Nonnull)message
                      option:(AgoraRtmTopicMessageOptions * _Nullable)options
                  completion:(AgoraRtmOperationBlock _Nullable)completionBlock
 // publishTopicMessage[2/2]
- (void) publishTopicMessage:(NSString * _Nonnull)topic
                        data:(NSData * _Nonnull)data
                      option:(AgoraRtmTopicMessageOptions * _Nullable)options
                  completion:(AgoraRtmOperationBlock _Nullable)completionBlock
ParametersTypeRequiredDefaultDescription
topicNSStringRequired-Topic name.
messageNSStringRequired-Sends string messages in the publishTopicMessage[1/2] method.
dataNSDataRequired-Sends binary messages in the publishTopicMessage[2/2] method.
optionsAgoraRtmTopicMessageOptionsOptional-Message options.
completionBlockAgoraRtmOperationBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmCommonResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

The AgoraRtmTopicMessageOptions data type contains the following properties:

PropertiesTypeRequiredDefaultDescription
sendTsunsigned long longOptional0The timestamp when the SDK sends a message. This parameter is only valid when you set syncWithMedia = true in the joinTopic method. The SDK synchronizes data with RTC audio and video streams based on this timestamp.
customTypeNSStringRequired-A user-defined field. Only supports NSString type.

Basic usage

Example 1: Send string messages to a specified channel.

NSString* message = @"Hello Agora!";
NSString* channel = @"your_channel";
[stream_channel publishTopicMessage:@"your_topic" message:raw_message option:nil completion:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"publish success!!");
    } else {
        NSLog(@"publish failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

Example 2: Send byte messages to a specified channel.

unsigned char byte_array[5] = {0,1,2,3,4};
NSData* raw_message = [[NSData alloc] initWithBytes:byte_array length:5];
NSString* channel = @"your_channel";
[stream_channel publishTopicMessage:@"your_topic" data:raw_message option:nil completion:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"publish success!!");
    } else {
        NSLog(@"publish failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

leaveTopic

Description

When you no longer need to publish messages to a topic, to release resources, you can call the leaveTopic method to unregister as a message publisher for that topic. This method does not affect whether or not you subscribe to that topic or any other operations performed by other users on that topic.

After successfully calling this method, users who subscribe to the channel and enable event listeners can receive the AgoraRtmTopicEventTypeRemoteLeaveTopic type of the didReceiveTopicEvent event notification. See Event Listeners.

Method

You can call the leaveTopic method as follows:

- (void) leaveTopic: (NSString * _Nonnull)topic
         completion: (AgoraRtmOperationBlock _Nullable)completionBlock;
ParametersTypeRequiredDefaultDescription
topicNSStringRequired-Topic name.
completionBlockAgoraRtmOperationBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmCommonResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

Basic usage

[stream_channel leaveTopic:@"your_topic" completion:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"leave topic success!!");
    } else {
        NSLog(@"leave topic failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);

    }
}];

subscribeTopic

Description

After joining the channel, you can call the subscribeTopic method to subscribe to the message publisher of the topic in the channel.

subscribeTopic is an incremental method. For example, if you call this method for the first time with a subscribing list of [UserA, UserB], and then call it again with a subscribing list of [UserB, UserC], the final successful subscribing result is [UserA, UserB, UserC].

A user can subscribe to a maximum of 50 topics in each channel, and a maximum of 64 message publishers in each topic. See API usage restrictions.

Method

You can call the subscribeTopic method as follows:

- (void) subscribeTopic:(NSString * _Nonnull)topic
                 option:(AgoraRtmTopicOption * _Nullable)option
             completion:(AgoraRtmTopicSubscriptionBlock _Nullable)completionBlock
ParametersTypeRequiredDefaultDescription
topicNSStringRequired-Topic name.
optionAgoraRtmTopicOptionOptional-Options for subscribing to a topic.
completionBlockAgoraRtmTopicSubscriptionBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmTopicSubscriptionResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

The AgoraRtmTopicOption data type contains the following properties:

PropertiesTypeRequiredDefaultDescription
usersNSArray&lt;NSString *&gt;Optional-A list of UserId of message publishers that you want to subscribe to. If you do not set this property, you can randomly subscribe to up to 64 users by default.

The AgoraRtmTopicSubscriptionResponse data type contains the following properties:

PropertiesTypeDescription
succeedUsersNSArray&lt;NSString *&gt;A list of successfully subscribed users.
failedUsersNSArray&lt;NSString *&gt;A list of users that the SDK fails to subscribe to.

Basic usage

Example 1: Subscribe to the specified message publisher in the topic.

AgoraRtmTopicOption* topic_opt = [[AgoraRtmTopicOption alloc] init];
topic_opt.users = @[@"user1", @"user2"];
[stream_channel subscribeTopic:@"your_topic" option:topic_opt completion:^(AgoraRtmTopicSubscriptionResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"subscribe topic success!!");
    } else {
        NSArray<NSString *> *sucees_users = response.succeedUsers;
        NSArray<NSString *> *fail_users = response.failedUsers;
        NSLog(@"subscribe topic failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

Example 2: Randomly subscribe to 64 message publishers in the topic.

[stream_channel subscribeTopic:@"your_topic" option:nil completion:^(AgoraRtmTopicSubscriptionResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"subscribe topic success!!");
    } else {
        NSLog(@"subscribe topic failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

unsubscribeTopic

Description

If you are no longer interested in a specified topic, or no longer need to subscribe to one or more message publishers in the topic, you can call the unsubscribeTopic method to unsubscribe from the topic or the specified message publishers in the topic.

Method

You can call the unsubscribeTopic method as follows:

- (void) unsubscribeTopic:(NSString * _Nonnull)topic
                   option:(AgoraRtmTopicOption * _Nullable)option
               completion:(AgoraRtmOperationBlock _Nullable)completionBlock
ParametersTypeRequiredDefaultDescription
topicNSStringRequired-Topic name.
optionsAgoraRtmTopicOptionOptional-Options for unsubscribe from a topic.
completionBlockAgoraRtmOperationBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmCommonResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

The AgoraRtmTopicOption data type contains the following properties:

PropertiesTypeRequiredDefaultDescription
usersNSArray&lt;NSString *&gt;Optional-A list of UserId of message publishers that you want to unsubscribe from. If you do not set this property, you can randomly unsubscribe from up to 64 users by default.

Basic usage

Example 1: Unsubscribe the specified message publisher in the topic

AgoraRtmTopicOption* topic_opt = [[AgoraRtmTopicOption alloc] init];
topic_opt.users = @[@"user1", @"user2"];
[stream_channel unsubscribeTopic:@"your_topic" option:topic_opt completion:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"subscribe topic success!!");
    } else {
        NSLog(@"subscribe topic failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

Example 2: Randomly unsubscribe 64 message publishers from the topic.

[stream_channel unsubscribeTopic:@"your_topic" option:nil completion:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"subscribe topic success!!");
    } else {
        NSLog(@"subscribe topic failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

Messages

Sending and receiving messages is the most basic function of the Signaling service. Any message sent by the Signaling server can be delivered to any online subscribing user within 100 ms. Depending on your business requirements, you can send messages to one user only or broadcast messages to multiple users.

Signaling offers 3 types of channels: message channels, user channels, and stream channels. These channel types have the following differences in how messages are transmitted and methods are called:

  • Message Channel: The real-time channel. Messages are transmitted through the channel, and the channel is highly scalable. Local users can call the publishTopicMessage method, set the channelType parameter to AgoraRtmChannelTypeMessage, and set the channelName parameter to the channel name to send messages in the channel. The remote users can call the subscribeTopic method to subscribe to the channel and receive messages.
  • User Channel: The real-time channel. Messages are transmitted to the specified user. Local users can call the publishTopicMessage method, set the channelType parameter to AgoraRtmChannelTypeUser, and set the channelName parameter to the user ID to send messages to the specified user. The specified remote users receive messages through the didReceiveMessageEvent event notifications.
  • Stream Channel: The streaming transmission channel. Messages are transmitted through the topic. Users need to join a channel first, and then join a topic. Local users can call the publishTopicMessage method to send messages in the topic, and remote users can call the subscribeTopic method to subscribe to the topic and receive messages.

This section introduces how to send and receive messages in a message channel or a user channel.

AgoraRtmClientKit Signaling client instance

publishTopicMessage

Description

You can directly call the publishTopicMessage method to send messages to all online users subscribed to this channel. Even if you do not subscribe to the channel, you can still send messages in the channel.

Information

The following practices can effectively improve the reliability of message transmission:
- The message payload should be within 32 KB; otherwise, the sending will fail.
- The upper limit of the rate at which messages are sent to a single channel is 60 QPS. If the sending rate exceeds the limit, some messages will be discarded. A lower rate is better, as long as the requirements are met.

After successfully calling this method, the SDK triggers a didReceiveMessageEvent event notification. Users who subscribe to the channel and enabled the event listener can receive this event notification. For details, see Event Listeners.

Method

You can call the publishTopicMessage [1/2] and publishTopicMessage [2/2] methods as follows:

 // publish[1/2]
- (void) publish:(NSString* _Nonnull)channelName
         message:(NSString* _Nonnull)message
          option:(AgoraRtmPublishOptions* _Nullable)publishOption
      completion:(AgoraRtmOperationBlock _Nullable)completionBlock
 // publish[2/2]
- (void) publish:(NSString* _Nonnull)channelName
            data:(NSData* _Nonnull)data
          option:(AgoraRtmPublishOptions* _Nullable)publishOption
      completion:(AgoraRtmOperationBlock _Nullable)completionBlock
ParametersTypeRequiredDefaultDescription
channelNameNSStringRequired-Fill in a channel name to send messages in a specified channel, or fill in a user ID to send messages to a specified user.
messageNSStringRequired-Sends string messages in the publishTopicMessage[1/2] method.
dataNSDataRequired-Sends binary messages in the publishTopicMessage[2/2] method.
publishOptionAgoraRtmTopicMessageOptionsOptional-Message options.
completionBlockAgoraRtmOperationBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmCommonResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

The AgoraRtmTopicMessageOptions data type contains the following properties:

PropertiesTypeRequiredDefaultDescription
channelTypeAgoraRtmChannelTypeRequired-Channel types. See AgoraRtmChannelType.
customTypeNSStringRequired-A user-defined field. Only supports string type.

Basic usage

Example 1: Send string messages to a specified channel.

NSString* message = @"Hello Agora!";
NSString* channel = @"your_channel";
[rtm publish:channel message:message option:nil completion:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"publish success!!");
    } else {
        NSLog(@"publish failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

Example 2: Send byte messages to a specified channel.

unsigned char byte_array[5] = {0,1,2,3,4};
NSData* raw_message = [[NSData alloc] initWithBytes:byte_array length:5];
NSString* channel = @"your_channel";
[rtm publish:channel data:raw_message option:nil completion:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"publish success!!");
    } else {
        NSLog(@"publish failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

Example 3: Send string messages to a specified user.

NSString* message = @"Hello Agora!";
NSString* user = @"Tony";

AgoraRtmPublishOptions* publish_option = [[AgoraRtmPublishOptions alloc] init];
publish_option.channelType = AgoraRtmChannelTypeUser;

[rtm publish:user message:message option:publish_option completion:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"publish success!!");
    } else {
        NSLog(@"publish failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

Example 4: Send byte messages to a specified user.

NSData* raw_message = [[NSData alloc] initWithBytes:byte_array length:5];
NSString* user = @"Tony";

AgoraRtmPublishOptions* publish_option = [[AgoraRtmPublishOptions alloc] init];
publish_option.channelType = AgoraRtmChannelTypeUser;

[rtm publish:user data:raw_message option:publish_option completion:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"publish success!!");
    } else {
        NSLog(@"publish failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

Information

After successfully calling this method, the SDK triggers a didReceiveMessageEvent event notification. Users who subscribe to the channel and enabled the event listener can receive this event notification. For details, see Event Listeners.

Receive

Signaling provides event notifications for messages, states, and event changes. By listening for callbacks, you can receive messages and events within subscribed channels. As an example, the code snippet below shows how to receive messages from the user channel.

  • Adding during initialization:
    @interface RtmHandler : NSObject <AgoraRtmClientDelegate>
    @end

    @implementation RtmHandler
    // triggered when received message from remote users
    -(void) rtmKit:(AgoraRtmClientKit *)rtmKit didReceiveMessageEvent:(AgoraRtmMessageEvent *)event {
        NSString* channel = event.channelName;
        AgoraRtmChannelType channel_type = event.channelType;
        if (channel_type == AgoraRtmChannelTypeUser) {
            // process user message
        }
    }
    @end

    AgoraRtmClientConfig* rtm_cfg = [[AgoraRtmClientConfig alloc] initWithAppId:@"your_appid" userId:@"your_userid"];

    RtmListener* handler =  [[RtmListener alloc] init];
    NSError* initError = nil;
    AgoraRtmClientKit* rtm = [[AgoraRtmClientKit alloc] initWithConfig:rtm_cfg delegate:handler error:&initError];
  • Adding at any time:
    @interface RtmHandler : NSObject <AgoraRtmClientDelegate>
    @end

    @implementation RtmHandler
    // triggered when received message from remote users
    -(void) rtmKit:(AgoraRtmClientKit *)rtmKit didReceiveMessageEvent:(AgoraRtmMessageEvent *)event {
        NSString* channel = event.channelName;
        AgoraRtmChannelType channel_type = event.channelType;
        if (channel_type == AgoraRtmChannelTypeUser) {
            // process user message
        }
    }
    @end

    RtmListener* handler =  [[RtmListener alloc] init];
    [rtm addDelegate:handler];

For information on how to add and set event listeners, see Event Listeners.

Presence

The presence feature provides the ability to monitor user online, offline, and user historical state change. With the Presence feature, you can get real-time access to the following information:

  • Real-time event notification when a user joins or leaves a specified channel.
  • Real-time event notification when the custom temporary user state changes.
  • Query which channels a specified user has joined or subscribed to.
  • Query which users have joined a specified channel and their temporary user state data.

Information

Presence applies to both message channels and stream channels.

AgoraRtmPresence Presence instance

getOnlineUsers

Description

By calling the getOnlineUsers method, you can query real-time information about the number of online users, the list of online users, and the temporary state of online users in a specified channel.

Method

You can call the getOnlineUsers method as follows:

-(void) getOnlineUsers: (NSString * _Nonnull) channelName
   channelType: (AgoraRtmChannelType)channelType
       options: (AgoraRtmGetOnlineUsersOptions* _Nullable)options
    completion: (AgoraRtmGetOnlineUsersBlock _Nullable)completionBlock;
ParametersTypeRequiredDefaultDescription
channelNameNSStringRequired-Channel name.
channelTypeAgoraRtmChannelTypeRequired-Channel types. See AgoraRtmChannelType.
optionsAgoraRtmGetOnlineUsersOptionsOptional-Query options.
completionBlockAgoraRtmGetOnlineUsersBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmGetOnlineUsersResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

The AgoraRtmGetOnlineUsersOptions data type contains the following properties:

PropertiesTypeRequiredDefaultDescription
includeUserIdBOOLOptionaltrueWhether the returned result includes the user ID of online members.
includeStateBOOLOptionalfalseWhether the returned result includes temporary state data of online users.
pageNSStringRequired-Page number of the returned result. You can check whether there is next page in the returned result.

The AgoraRtmGetOnlineUsersResponse data type contains the following properties:

PropertiesTypeDescription
totalOccupancyintThe list length of UserStateList. When you set both includeUserId and includeState properties in the AgoraRtmGetOnlineUsersOptions data type to false, this value represents the total number of current online users in the channel.
userStateListNSArray&lt;AgoraRtmUserState *&gt;List of online users and their temporary state information in a specified channel.
nextPageNSStringPage number of the next page. Confirm whether there is a next page:
- A null value indicates that next page does not exist.
- A non-null value indicates that there is a next page. You can fill this value in the page property of the getOnlineUsers method to query the next page results.

The AgoraRtmUserState data type contains the following properties:

PropertiesTypeDescription
userIdNSStringUser ID.
statesNSDictionaryList of online users and their temporary state information in a specified channel.

AgoraRtmStateItem data type contains the following properties:

PropertiesTypeDescription
keyNSStringKey of the user state. If the specified key already exists, the SDK overwrites the value; if the specified key does not exist, the SDK creates the key-value pair.
valueNSStringValue of the user state.

Basic usage

AgoraRtmGetOnlineUsersOptions* presence_opt = [[AgoraRtmPresence alloc] init];
presence_opt.includeState = false;
presence_opt.includeUserId = false;

[[rtm getPresence] getOnlineUsers:@"your_channel" channelType:AgoraRtmChannelTypeMessage options:presence_opt completion:^(AgoraRtmGetOnlineUsersResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"getOnlineUsers success!!");
        int user_count = response.totalOccupancy;
    } else {
        NSLog(@"getOnlineUsers failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

getUserChannels

Description

In use-cases such as statistic analytics and debugging, you may need to know all the channels that a specified user has subscribed to or joined. Call the getUserChannels method to get the list of channels where the specified user is in real time.

Method

You can call the getUserChannels method as follows:

-(void) getUserChannels: (NSString * _Nonnull) userId
      completion: (AgoraRtmGetUserChannelsBlock _Nullable)completionBlock;
ParametersTypeRequiredDefaultDescription
userIdNSStringRequired-User ID.
completionBlockAgoraRtmGetUserChannelsBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmGetUserChannelsResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

The AgoraRtmGetUserChannelsResponse data type contains the following properties:

PropertiesTypeDescription
totalChannelintNumber of channels the user is in.
channelsNSArray&lt;AgoraRtmChannelInfo *&gt;List of channel information, including channel name and channel type.

The AgoraRtmChannelInfo data type contains the following properties:

PropertiesTypeDescription
channelNameNSStringChannel name.
channelTypeAgoraRtmChannelTypeChannel types. See AgoraRtmChannelType.

Basic usage

[[rtm getPresence] getUserChannels:@"userId" completion:^(AgoraRtmGetUserChannelsResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"getUserChannels success!!");
        int channel_count = response.totalChannel;
        NSArray<AgoraRtmChannelInfo *> * channels = response.channels;
    } else {
        NSLog(@"getUserChannels failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

setState

Description

To meet different requirements in different business use-cases for setting user states, Signaling provides the setState method to customize the temporary user state. Users can add custom states such as scores, game state, location, mood, and hosting state for themselves.

After successful setup, as long as the user keeps subscribing to the channel and stays online, the custom states can persist in the channel. setState method sets the temporary user state, and the state disappears when the user leaves the channel or disconnects from Signaling. If you need to restore user states when rejoining a channel or reconnecting, you need to cache the data locally in real time. If you want to permanently save user states, Agora recommends you use the setUserMetadata method of the storage function instead.

If a user modifies the temporary user state, Signaling triggers the AgoraRtmPresenceEventTypeRemoteStateChanged type of the didReceivePresenceEvent event in real time. You can receive the event by subscribing to the channel and configuring the corresponding property.

Method

You can call the setState method as follows:

-(void) setState: (NSString * _Nonnull) channelName
     channelType: (AgoraRtmChannelType)channelType
           items: (NSArray<AgoraRtmStateItem *> * _Nonnull) items
      completion: (AgoraRtmOperationBlock _Nullable)completionBlock;
ParametersTypeRequiredDefaultDescription
channelNameNSStringRequired-Channel name
channelTypeAgoraRtmChannelTypeRequired-Channel types. See AgoraRtmChannelType.
itemsNSDictionaryRequired-User state, an array of StateItem.
completionBlockAgoraRtmOperationBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmCommonResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

Basic usage

NSDictionary *states = @{@"key1": @"value1", @"key2": @"value2"};

[[rtm getPresence] setState:@"your_channel" channelType:AgoraRtmChannelTypeMessage items:states completion:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"setState success!!");
    } else {
        NSLog(@"setState failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

getState

Description

To get the temporary user state of a specified user in the channel, you can use the getState method.

Method

You can call the getState method as follows:

-(void) getState: (NSString * _Nonnull) channelName
     channelType: (AgoraRtmChannelType)channelType
          userId: (NSString * _Nonnull) userId
      completion: (AgoraRtmPresenceGetStateBlock _Nullable)completionBlock;
ParametersTypeRequiredDefaultDescription
channelNameNSStringRequired-Channel name.
channelTypeAgoraRtmChannelTypeRequired-Channel types. See AgoraRtmChannelType.
userIdNSStringRequired-User ID.
completionBlockAgoraRtmPresenceGetStateBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmPresenceGetStateResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

The AgoraRtmPresenceGetStateResponse data type contains the following properties:

PropertiesTypeDescription
stateAgoraRtmUserStateList of online users and their temporary state information in a specified channel.

The AgoraRtmUserState data type contains the following properties:

PropertiesTypeDescription
userIdNSStringUser ID.
statesNSDictionaryList of online users and their temporary state information in a specified channel.

AgoraRtmStateItem data type contains the following properties:

PropertiesTypeDescription
keyNSStringKey of the user state. If the specified key already exists, the SDK overwrites the value; if the specified key does not exist, the SDK creates the key-value pair.
valueNSStringValue of the user state.

Basic usage

[[rtm getPresence] getState:@"your_channel" channelType:AgoraRtmChannelTypeMessage userId:@"userid" completion:^(AgoraRtmPresenceGetStateResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"getState success!!");
        AgoraRtmUserState* state = response.state;
    } else {
        NSLog(@"getState failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

removeState

Description

When a temporary user state is no longer needed, you can call the removeState method to remove one or more of your temporary states. When the user state is removed, the user who has subscribed to the channel and enabled the presence event listener receives the AgoraRtmPresenceEventTypeRemoteStateChanged type of didReceivePresenceEvent event notification. See Event Listeners.

Method

You can call the removeState method as follows:

-(void) removeState:(NSString * _Nonnull)channelName
        channelType:(AgoraRtmChannelType)channelType
               keys:(NSArray<NSString *> * _Nonnull)keys
         completion:(AgoraRtmOperationBlock _Nullable)completionBlock
ParametersTypeRequiredDefaultDescription
channelNameNSStringRequired-Channel name
channelTypeAgoraRtmChannelTypeRequired-Channel types. See AgoraRtmChannelType.
keysNSArray&lt;NSString *&gt;Required-List of keys to be deleted. If you do not provide this property, the SDK removes all states.
completionBlockAgoraRtmOperationBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmCommonResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

Basic usage

NSArray<NSString*>* keys = @[@"key1", @"key2"];
[[rtm getPresence] removeState:@"your_channel" channelType:AgoraRtmChannelTypeMessage keys:keys completion:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"removeState success!!");
    } else {
        NSLog(@"removeState failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

Storage

The storage feature provides a database mechanism that allows developers to dynamically set, store, update, and delete data such as channel metadata and user metadata.

AgoraRtmStorage Storage instance

setChannelMetadata

Description

The setChannelMetadata method sets metadata for a message channel or stream channel. A channel can only have one set of metadata, but each set of metadata can have one or more metadata items. If you call this method multiple times, the SDK retrieves the key of the metadata items in turn and apply settings according to the following rules:

  • If you set metadata with different key, the SDK adds each set of metadata in sequence according to the order of the method calls.
  • If you set metadata with the same key, the value of the last setting overwrites the previous one.

After successfully setting channel metadata, users who subscribe to the channel and enable event listeners can receive the AgoraRtmStorageTypeChannel type of the didReceiveStorageEvent event notification. See Event listeners.

Channel metadata also introduces the version control logic CAS (Compare And Set). This method provides two independent version control fields, and you can set one or more of them according to your actual business use-case:

  • Enable version number verification for the entire set of channel metadata by setting the majorRevision property in the AgoraRtmMetadata data type.
  • Enable version number verification for a single metadata item by setting the revision property in the AgoraRtmMetadataItem class.

When setting channel metadata or metadata items, you can control whether to enable version number verification by specifying the revision property:

  • The default value of the revision property is -1, indicating that this method call does not perform any CAS verification. If the channel metadata or metadata item already exists, the latest value overwrites the previous one. If the channel metadata or metadata item does not exist, the SDK creates it.
  • If the revision property is a positive integer, this method call performs the CAS verification. If the channel metadata or metadata item already exists, the SDK updates the corresponding value after the version number verification succeeds. If the channel metadata or metadata item does not exist, the SDK returns the error code.

Method

You can call the setChannelMetadata method as follows:

- (void) setChannelMetadata: (NSString * _Nonnull)channelName
                channelType: (AgoraRtmChannelType)channelType
                       data: (AgoraRtmMetadata* _Nonnull)data
                    options: (AgoraRtmMetadataOptions* _Nullable)options
                       lock: (NSString * _Nullable)lock
                 completion: (AgoraRtmOperationBlock _Nullable)completionBlock;
ParametersTypeRequiredDefaultDescription
channelNameNSStringRequired-Channel name.
channelTypeAgoraRtmChannelTypeRequired-Channel types. See AgoraRtmChannelType.
dataAgoraRtmMetadataRequired-Metadata item. See AgoraRtmMetadata.
optionsAgoraRtmMetadataOptionsOptional-Options for setting the channel metadata.
lockNSStringOptionalnil string ''Lock name. If set, only users who call the acquireLock method to acquire the lock can perform operations.
completionBlockAgoraRtmOperationBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmCommonResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

The AgoraRtmMetadataOptions data type contains the following properties:

PropertiesTypeRequiredDefaultDescription
recordTsBOOLOptionalfalseWhether to record the timestamp of the edits.
recordUserIdBOOLOptionalfalseWhether to record the user ID of the editor.

Basic usage

 //get metadata
AgoraRtmMetadata* metadata = [[AgoraRtmMetadata alloc] init];

 //set metadata items
AgoraRtmMetadataItem* apple = [[AgoraRtmMetadataItem alloc] init];
apple.key = @"Apple";
apple.value = @"100";
apple.revision = 174298200;
AgoraRtmMetadataItem* banana = [[AgoraRtmMetadataItem alloc] init];
banana.key = @"Banana";
banana.value = @"200";
banana.revision = 174298100;

NSArray *item_array = [NSArray arrayWithObjects:apple,banana];
metadata.items = item_array;
metadata.majorRevision = 174298100;

AgoraRtmMetadataOptions* metadata_opt = [[AgoraRtmMetadataOptions alloc] init];
metadata_opt.recordUserId = true;
metadata_opt.recordTs = true;

[[rtm getStorage] setChannelMetadata:@"channel_name" channelType:AgoraRtmChannelTypeMessage data:metadata options:metadata_opt lock:@"lockName" completion:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"setChannelMetadata success!!");
    } else {
        NSLog(@"setChannelMetadata failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

getChannelMetadata

Description

The getChannelMetadata method can get the metadata of the specified channel.

Method

You can call the getChannelMetadata method as follows:

- (void) getChannelMetadata: (NSString * _Nonnull)channelName
                channelType: (AgoraRtmChannelType)channelType
                 completion: (AgoraRtmGetMetadataBlock _Nullable)completionBlock;
ParametersTypeRequiredDefaultDescription
channelNameNSStringRequired-Channel name.
channelTypeAgoraRtmChannelTypeRequired-Channel types. See AgoraRtmChannelType.
completionBlockAgoraRtmGetMetadataBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmGetMetadataResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

The AgoraRtmGetMetadataResponse data type contains the following properties:

PropertiesTypeDescription
dataAgoraRtmMetadataMetadata item. See AgoraRtmMetadata.

Basic usage

[[rtm getStorage] getChannelMetadata:@"channel_name" channelType:AgoraRtmChannelTypeMessage completion:^(AgoraRtmGetMetadataResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"getChannelMetadata success!!");
        AgoraRtmMetadata* data = response.data; //get storage data;
        NSArray<AgoraRtmMetadataItem *> * items = [data getMetadataItems];
        for (int i = 0; i < items.count; i++) {
            NSLog(@"key: %@ value: %@ revision: %lld", items[i].key, items[i].value, items[i].revision);
        }

    } else {
        NSLog(@"getChannelMetadata failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

removeChannelMetadata

Description

The removeChannelMetadata method can remove channel metadata or metadata items.

When removing channel metadata or metadata items, you can control whether to enable version number verification by specifying the revision property:

  • The default value of the revision property is -1, indicating that this method call does not perform any CAS verification. If the channel metadata or metadata item already exists, the SDK removes it. If the channel metadata or metadata item does not exist, the SDK returns the error code.
  • If the revision property is a positive integer, this method call performs the CAS verification. If the channel metadata or metadata item already exists, the SDK removes the corresponding value after the version number verification succeeds. If the channel metadata or metadata item does not exist, the SDK returns the error code.

After successfully removing channel metadata or metadata items, users who subscribe to the channel and enable event listeners can receive the AgoraRtmStorageTypeChannel type of the didReceiveStorageEvent event notification. See Event listeners.

Method

You can call the removeChannelMetadata method as follows:

- (void) removeChannelMetadata: (NSString * _Nonnull)channelName
                   channelType: (AgoraRtmChannelType)channelType
                          data: (AgoraRtmMetadata* _Nonnull)data
                       options: (AgoraRtmMetadataOptions* _Nullable)options
                          lock: (NSString * _Nullable)lock
                    completion: (AgoraRtmOperationBlock _Nullable)completionBlock;
ParametersTypeRequiredDefaultDescription
channelNameNSStringRequired-Channel name.
channelTypeAgoraRtmChannelTypeRequired-Channel types. See AgoraRtmChannelType.
dataAgoraRtmMetadataRequired-Metadata item. See AgoraRtmMetadata.
optionsAgoraRtmMetadataOptionsOptional-Options for setting the channel metadata.
lockNSStringOptionalnil string ''Lock name. If set, only users who call the acquireLock method to acquire the lock can perform operations.
completionBlockAgoraRtmOperationBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmCommonResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

The AgoraRtmMetadataOptions data type contains the following properties:

PropertiesTypeRequiredDefaultDescription
recordTsBOOLOptionalfalseWhether to record the timestamp of the edits.
recordUserIdBOOLOptionalfalseWhether to record the user ID of the editor.

Basic usage

AgoraRtmMetadata* metadata = [[AgoraRtmMetadata alloc] init];

AgoraRtmMetadataItem* apple = [[AgoraRtmMetadataItem alloc] init];
apple.key = @"Apple";
apple.revision = 174298200;

NSArray *item_array = [NSArray arrayWithObjects:apple];
metadata.items = item_array;
metadata.majorRevision = 174298100;

[[rtm getStorage] removeChannelMetadata:@"channel_name" channelType:AgoraRtmChannelTypeMessage data:metadata options:metadata_opt lock:nil completion:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"removeChannelMetadata success!!");
    } else {
        NSLog(@"removeChannelMetadata failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

updateChannelMetadata

Description

The updateChannelMetadata method can update existing channel metadata. Each time you call this method, you can update one channel metadata or a channel metadata item.

After successfully updating channel metadata, users who subscribe to the channel and enable event listeners can receive the AgoraRtmStorageTypeChannel type of the didReceiveStorageEvent event notification. See Event listeners.

Information

You cannot use this method to update metadata items which do not exist.

Method

You can call the updateChannelMetadata method as follows:

- (void) updateChannelMetadata: (NSString * _Nonnull)channelName
                   channelType: (AgoraRtmChannelType)channelType
                          data: (AgoraRtmMetadata* _Nonnull)data
                       options: (AgoraRtmMetadataOptions* _Nullable)options
                          lock: (NSString * _Nullable)lock
                    completion: (AgoraRtmOperationBlock _Nullable)completionBlock;
ParametersTypeRequiredDefaultDescription
channelNameNSStringRequired-Channel name.
channelTypeAgoraRtmChannelTypeRequired-Channel types. See AgoraRtmChannelType.
dataAgoraRtmMetadataRequired-Metadata item. See AgoraRtmMetadata.
optionsAgoraRtmMetadataOptionsOptional-Options for setting the channel metadata.
lockNSStringOptionalnil string ''Lock name. If set, only users who call the acquireLock method to acquire the lock can perform operations.
completionBlockAgoraRtmOperationBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmCommonResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

The AgoraRtmMetadataOptions data type contains the following properties:

PropertiesTypeRequiredDefaultDescription
recordTsBOOLOptionalfalseWhether to record the timestamp of the edits.
recordUserIdBOOLOptionalfalseWhether to record the user ID of the editor.

Basic usage

// get metadata
AgoraRtmMetadata* metadata = [[AgoraRtmMetadata alloc] init];

// set metadata items
AgoraRtmMetadataItem* apple = [[AgoraRtmMetadataItem alloc] init];
apple.key = @"Apple";
apple.value = @"120";
apple.revision = 174298200;
AgoraRtmMetadataItem* banana = [[AgoraRtmMetadataItem alloc] init];
banana.key = @"Banana";
banana.value = @"220";
banana.revision = 174298100;

NSArray *item_array = [NSArray arrayWithObjects:apple,banana];
metadata.items = item_array;
metadata.majorRevision = 174298100;

AgoraRtmMetadataOptions* metadata_opt = [[AgoraRtmMetadataOptions alloc] init];
metadata_opt.recordUserId = true;
metadata_opt.recordTs = true;

[[rtm getStorage] updateChannelMetadata:@"channel_name" channelType:AgoraRtmChannelTypeMessage data:metadata options:metadata_opt lock:@"lockName" completion:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"updateChannelMetadata success!!");
    } else {
        NSLog(@"updateChannelMetadata failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

setUserMetadata

Description

The setUserMetadata method can set metadata for a user. If you call this method multiple times, the SDK retrieves the key of the metadata items in turn and apply settings according to the following rules:

  • If you set metadata with different key, the SDK adds each set of metadata in sequence according to the order of the method calls.
  • If you set metadata with the same key, the value of the last setting overwrites the previous one.

After successfully setting user metadata, users who subscribe to the user and enable event listeners can receive the AgoraRtmStorageTypeUser type of the didReceiveStorageEvent event notification. See Event listeners.

User metadata also introduces the version control logic CAS (Compare And Set). This method provides two independent version control fields, and you can set one or more of them according to your actual business use-case:

  • Enable version number verification for the entire set of channel metadata by setting the majorRevision property in the AgoraRtmMetadata data type.
  • Enable version number verification for a single metadata item by setting the revision property in the AgoraRtmMetadataItem class.

When setting user metadata or metadata items, you can control whether to enable version number verification by specifying the revision property:

  • The default value of the revision property is -1, indicating that this method call does not perform any CAS verification. If the user metadata or metadata item already exists, the latest value overwrites the previous one. If the user metadata or metadata item does not exist, the SDK creates it.
  • If the revision property is a positive integer, this method call performs the CAS verification. If the user metadata or metadata item already exists, the SDK updates the corresponding value after the version number verification succeeds. If the user metadata or metadata item does not exist, the SDK returns the error code.

Method

You can call the setUserMetadata method as follows:

- (void) setUserMetadata: (NSString * _Nonnull)userId
                    data: (AgoraRtmMetadata* _Nonnull)data
                 options: (AgoraRtmMetadataOptions* _Nullable)options
              completion: (AgoraRtmOperationBlock _Nullable)completionBlock;
ParametersTypeRequiredDefaultDescription
userIdNSStringRequireduserId of the current userUser ID.
dataAgoraRtmMetadataRequired-Metadata item. See AgoraRtmMetadata.
optionsAgoraRtmMetadataOptionsOptional-Options for setting the channel metadata.
completionBlockAgoraRtmOperationBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmCommonResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

The AgoraRtmMetadataOptions data type contains the following properties:

PropertiesTypeRequiredDefaultDescription
recordTsBOOLOptionalfalseWhether to record the timestamp of the edits.
recordUserIdBOOLOptionalfalseWhether to record the user ID of the editor.

Basic usage

AgoraRtmMetadata* metadata = [[AgoraRtmMetadata alloc] init];

AgoraRtmMetadataItem* name = [[AgoraRtmMetadataItem alloc] init];
name.key = @"Name";
name.value = @"Tony";
name.revision = 174298200;
AgoraRtmMetadataItem* mute = [[AgoraRtmMetadataItem alloc] init];
mute.key = @"Mute";
mute.value = @"true";
mute.revision = 174298100;

NSArray *item_array = [NSArray arrayWithObjects:name,mute];
metadata.items = item_array;
metadata.majorRevision = 174298200;

AgoraRtmMetadataOptions* metadata_opt = [[AgoraRtmMetadataOptions alloc] init];
metadata_opt.recordUserId = true;
metadata_opt.recordTs = true;
[[rtm getStorage] setUserMetadata:@"Tony" data:metadata options:metadata_opt completion:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"setUserMetadata success!!");
    } else {
        NSLog(@"setUserMetadata failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

getUserMetadata

Description

The getUserMetadata method can get the metadata and metadata item for the specified user.

Method

You can call the getUserMetadata method as follows:

- (void) getUserMetadata: (NSString * _Nonnull)userId
              completion: (AgoraRtmGetMetadataBlock _Nullable)completionBlock;
ParametersTypeRequiredDefaultDescription
userIdNSStringRequireduserId of the current userUser ID.
completionBlockAgoraRtmGetMetadataBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmGetMetadataResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

The AgoraRtmGetMetadataResponse data type contains the following properties:

PropertiesTypeDescription
dataAgoraRtmMetadataMetadata item. See AgoraRtmMetadata.

Basic usage

[[rtm getStorage] getUserMetadata:@"Tony" completion:^(AgoraRtmGetMetadataResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"getUserMetadata success!!");
        AgoraRtmMetadata* data = response.data; //get storage data;
        NSArray<AgoraRtmMetadataItem *> * items = [data getMetadataItems];
        for (int i = 0; i < items.count; i++) {
            NSLog(@"key: %@ value: %@ revison: %lld", items[i].key, items[i].value, items[i].revision);
        }
    } else {
        NSLog(@"getUserMetadata failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

removeUserMetadata

Description

The removeUserMetadata method can remove user metadata or metadata items.

After successfully removing user metadata, users who subscribe to the user and enable event listeners can receive the AgoraRtmStorageTypeUser type of the didReceiveStorageEvent event notification. See Event listeners.

Method

You can call the removeUserMetadata method as follows:

- (void) removeUserMetadata: (NSString * _Nonnull)userId
                       data: (AgoraRtmMetadata* _Nonnull)data
                    options: (AgoraRtmMetadataOptions* _Nullable)options
                 completion: (AgoraRtmOperationBlock _Nullable)completionBlock;
ParametersTypeRequiredDefaultDescription
userIdNSStringRequireduserId of the current userUser ID.
dataAgoraRtmMetadataRequired-Metadata item. See AgoraRtmMetadata.
optionsAgoraRtmMetadataOptionsOptional-Options for setting the channel metadata.
completionBlockAgoraRtmOperationBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmCommonResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

The AgoraRtmMetadataOptions data type contains the following properties:

PropertiesTypeRequiredDefaultDescription
recordTsBOOLOptionalfalseWhether to record the timestamp of the edits.
recordUserIdBOOLOptionalfalseWhether to record the user ID of the editor.

Basic usage

AgoraRtmMetadata* metadata = [[AgoraRtmMetadata alloc] init];

AgoraRtmMetadataItem* mute = [[AgoraRtmMetadataItem alloc] init];
mute.key = @"Mute";
mute.revision = 174298100;

NSArray *item_array = [NSArray arrayWithObjects:mute];
metadata.items = item_array;
metadata.majorRevision = 174298100;

[[rtm getStorage] removeUserMetadata:@"Tony" data:metadata options:nil completion:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"removeUserMetadata success!!");
    } else {
        NSLog(@"removeUserMetadata failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

updateUserMetadata

Description

The updateUserMetadata method can update existing user metadata. After successfully updating channel metadata, users who subscribe to the user and enable event listeners can receive the AgoraRtmStorageTypeUser type of the didReceiveStorageEvent event notification. See Event listeners.

Information

You cannot use this method to update metadata items which do not exist.

Method

You can call the updateUserMetadata method as follows:

- (void) updateUserMetadata: (NSString * _Nonnull)userId
                       data: (AgoraRtmMetadata* _Nonnull)data
                    options: (AgoraRtmMetadataOptions* _Nullable)options
                 completion: (AgoraRtmOperationBlock _Nullable)completionBlock;
ParametersTypeRequiredDefaultDescription
userIdNSStringRequireduserId of the current userUser ID.
dataAgoraRtmMetadataRequired-Metadata item. See AgoraRtmMetadata.
optionsAgoraRtmMetadataOptionsOptional-Options for setting the channel metadata.
completionBlockAgoraRtmOperationBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmCommonResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

The AgoraRtmMetadataOptions data type contains the following properties:

PropertiesTypeRequiredDefaultDescription
recordTsBOOLOptionalfalseWhether to record the timestamp of the edits.
recordUserIdBOOLOptionalfalseWhether to record the user ID of the editor.

Basic usage

AgoraRtmMetadata* metadata = [[AgoraRtmMetadata alloc] init];

AgoraRtmMetadataItem* mute = [[AgoraRtmMetadataItem alloc] init];
mute.key = @"Mute";
mute.value = @"false";
mute.revision = 174298100;

NSArray *item_array = [NSArray arrayWithObjects:mute];
metadata.items = item_array;
metadata.majorRevision = 174298100;

AgoraRtmMetadataOptions* metadata_opt = [[AgoraRtmMetadataOptions alloc] init];
metadata_opt.recordUserId = true;
metadata_opt.recordTs = true;

[[rtm getStorage] updateUserMetadata:@"Tony" data:metadata options:metadata_opt completion:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"updateUserMetadata success!!");
    } else {
        NSLog(@"updateUserMetadata failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

subscribeUserMetadata

Description

The subscribeUserMetadata method can subscribe to metadata for a specified user. After successfully subscribing to the user metadata, you can receive the AgoraRtmStorageTypeUser type of the didReceiveStorageEvent event notification when the metadata for that user changes. See Event listeners.

Method

You can call the subscribeUserMetadata method as follows:

- (void) subscribeUserMetadata: (NSString * _Nonnull)userId
                    completion: (AgoraRtmOperationBlock _Nullable)completionBlock;
ParametersTypeRequiredDefaultDescription
userIdNSStringRequireduserId of the current userUser ID.
completionBlockAgoraRtmOperationBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmCommonResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

Basic usage

[[rtm getStorage] subscribeUserMetadata:@"Tony" completion:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"subscribeUserMetadata success!!");
    } else {
        NSLog(@"subscribeUserMetadata failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

unsubscribeUserMetadata

Description

If you do not need to receive notifications of changes to a user metadata, call the unsubscribeUserMetadata method to unsubscribe.

Method

You can call the unsubscribeUserMetadata method as follows:

- (void) unsubscribeUserMetadata: (NSString * _Nonnull)userId
                      completion: (AgoraRtmOperationBlock _Nullable)completionBlock;
ParametersTypeRequiredDefaultDescription
userIdNSStringRequireduserId of the current userUser ID.
completionBlockAgoraRtmOperationBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmCommonResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

Basic usage

[[rtm getStorage] unsubscribeUserMetadata:@"Tony" completion:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"unsubscribeUserMetadata success!!");
    } else {
        NSLog(@"unsubscribeUserMetadata failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

AgoraRtmMetadata

Use the AgoraRtmMetadata data type to set and manage metadata, containing the following properties:

PropertiesTypeRequiredDefaultDescription
majorRevisionlong longOptional-1The version control switch:
- -1: Disable the version verification.
- > 0: Enable the version verification. The operation can only be performed if the target version number matches this value.
itemsNSArray&lt;AgoraRtmMetadataItem *&gt;OptionalnilMetadata items.

The AgoraRtmMetadataItem data type contains the following properties:

PropertiesTypeRequiredDefaultDescription
keyNSStringRequired-Key.
valueNSStringRequired-Value.
authorUserIdNSStringRequired-The user ID of the editor. This value is read-only and does not support writing.
revisionlong longOptional-1
- Returns the real version number in read operations.
- Serves as a version control switch in write operations:
- -1: Disable the version verification.
- > 0: Enable version verification, only perform the operation if the target version number matches this value.
updateTslong longOptional0Update timestamp. This value is read-only and does not support writing.

Lock

A critical resource can only be used by one process at a time. If a critical resource is shared between different processes, each process needs to adopt a mutually exclusive method to prevent mutual interference. Signaling provides a full set of lock solutions. By controlling different processes in a distributed system, you can solve the competition problem when users access shared resources.

Information

The client is able to set, remove, and revoke locks. Best practice is to control the permissions of these operations on the client side based on your business needs.

AgoraRtmLock Lock instance

setLock

Description

You need to configure the lock name, time to live (TTL) and other parameters by calling the setLock method. If the configuration succeeds, all users in the channel receives the didReceiveLockEvent event notifications of the AgoraRtmLockEventTypeLockSet type. For details, see Event Listeners.

Method

You can call the setLock method as follows:

-(void) setLock: (NSString * _Nonnull) channelName
    channelType: (AgoraRtmChannelType) channelType
       lockName: (NSString * _Nonnull) lockName
            ttl: (int) ttl
     completion: (AgoraRtmOperationBlock _Nullable)completionBlock;
ParametersTypeRequiredDefaultDescription
channelNameNSStringRequired-Channel name.
channelTypeAgoraRtmChannelTypeRequired-Channel types. See AgoraRtmChannelType.
lockNameNSStringRequired-Lock name.
ttlintOptional10The expiration time of the lock. The value is in seconds, ranging from [10 to 300]. When the user who owns the lock goes offline, if the user returns to the channel within the time they can still use the lock; otherwise, the lock is released and the users who listen for the didReceiveLockEvent event receives the AgoraRtmLockEventTypeLockReleased event.
completionBlockAgoraRtmOperationBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmCommonResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

Basic usage

long ttl = 30;
[[rtm getLock] setLock:@"my_channel" channelType:AgoraRtmChannelTypeStream lockName:@"my_lock" ttl:ttl completion:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"setLock success!!");
    } else {
        NSLog(@"setLock failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

acquireLock

Description

After successfully configuring a lock, you can call the acquireLock method on the client to acquire the right to own the lock. When you acquire the lock, other users in the channel receives the AgoraRtmLockEventTypeLockAcquired type of the didReceiveLockEvent event. For details, see Event Listeners.

Method

You can call the acquireLock method as follows:

-(void) acquireLock: (NSString * _Nonnull) channelName
        channelType: (AgoraRtmChannelType)channelType
           lockName: (NSString * _Nonnull) lockName
              retry: (BOOL) retry
         completion: (AgoraRtmOperationBlock _Nullable)completionBlock;
ParametersTypeRequiredDefaultDescription
channelNameNSStringRequired-Channel name.
channelTypeAgoraRtmChannelTypeRequired-Channel types. See AgoraRtmChannelType.
lockNameNSStringRequired-Lock name.
retryBOOLRequired-If the lock acquisition fails, whether to retry until the acquisition succeeds or the user leaves the channel.
completionBlockAgoraRtmOperationBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmCommonResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

Basic usage

BOOL retry = false;
[[rtm getLock] acquireLock:@"my_channel" channelType:AgoraRtmChannelTypeStream lockName:@"my_lock" retry:retry completion:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"acquireLock success!!");
    } else {
        NSLog(@"acquireLock failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

releaseLock

Description

When a user no longer needs to own a lock, the user can call the releaseLock method on the client side to release the lock. After successful release the lock, other users in the channel receives the AgoraRtmLockEventTypeLockReleased type of the didReceiveLockEvent event. See Event Listeners.

At this time, if other users want to acquire the lock, they can call the acquireLock method on the client side to compete. New users acquiring locks have the same contention priority as the users who set the retry property to automatically retry to acquire locks.

Method

You can call the releaseLock method as follows:

-(void) releaseLock: (NSString * _Nonnull) channelName
        channelType: (AgoraRtmChannelType)channelType
           lockName: (NSString * _Nonnull) lockName
         completion: (AgoraRtmOperationBlock _Nullable)completionBlock;
ParametersTypeRequiredDefaultDescription
channelNameNSStringRequired-Channel name.
channelTypeAgoraRtmChannelTypeRequired-Channel types. See AgoraRtmChannelType.
lockNameNSStringRequired-Lock name.
completionBlockAgoraRtmOperationBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmCommonResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

Basic usage

[[rtm getLock] releaseLock:@"my_channel" channelType:AgoraRtmChannelTypeStream lockName:@"my_lock" completion:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"releaseLock success!!");
    } else {
        NSLog(@"releaseLock failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

revokeLock

Description

When the lock is occupied, to ensure that your business is not affected, you may need to revoke the lock and give other users a chance to obtain it. Revoke the occupied lock by calling revokeLock. When the lock is revoked, all users in the channel receives the AgoraRtmLockEventTypeLockReleased type of the didReceiveLockEvent event. See Event Listeners.

At this time, if other users want to acquire the lock, they can call the acquireLock method on the client side to compete. New users acquiring locks have the same contention priority as the users who set the retry property to automatically retry to acquire locks.

Method

You can call the revokeLock method as follows:

-(void) revokeLock: (NSString * _Nonnull) channelName
       channelType: (AgoraRtmChannelType)channelType
          lockName: (NSString * _Nonnull) lockName
            userId: (NSString * _Nonnull) userId
        completion: (AgoraRtmOperationBlock _Nullable)completionBlock;
ParametersTypeRequiredDefaultDescription
channelNameNSStringRequired-Channel name.
channelTypeAgoraRtmChannelTypeRequired-Channel types. See AgoraRtmChannelType.
lockNameNSStringRequired-Lock name.
userIdNSStringRequired-The ID of the user who has a lock.
completionBlockAgoraRtmOperationBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmCommonResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

Basic usage

[[rtm getLock] revokeLock:@"my_channel" channelType:AgoraRtmChannelTypeStream lockName:@"my_lock" userId:@"lock_owner" completion:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"revokeLock success!!");
    } else {
        NSLog(@"revokeLock failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

getMessages

Description

If you want to query the lock information such as lock total number, lock name, and lock user, time to live, you can call the getMessages method on the client.

Method

You can call the getMessages method as follows:

-(void) getLocks: (NSString * _Nonnull) channelName
     channelType: (AgoraRtmChannelType)channelType
      completion: (AgoraRtmGetLocksBlock _Nullable)completionBlock;
ParametersTypeRequiredDefaultDescription
channelNameNSStringRequired-Channel name.
channelTypeAgoraRtmChannelTypeRequired-Channel types. See AgoraRtmChannelType.
completionBlockAgoraRtmGetLocksBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmGetLocksResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

The AgoraRtmGetLocksResponse data type contains the following properties:

PropertiesTypeDescription
lockDetailListNSArray&lt;AgoraRtmLockDetail *&gt;Lock details array.

The AgoraRtmLockDetail data type contains the following properties:

PropertiesTypeDescription
lockNameNSStringLock name.
ownerNSStringThe ID of the user who has a lock.
ttlintThe expiration time of the lock. The value is in seconds, ranging from [10 to 300]. When the user who owns the lock goes offline, if the user returns to the channel within the time they can still use the lock; otherwise, the lock is released and the users who listen for the didReceiveLockEvent event receives the AgoraRtmLockEventTypeLockReleased event.

Basic usage

[[rtm getLock] getLocks:@"my_channel" channelType:AgoraRtmChannelTypeStream completion:^(AgoraRtmGetLocksResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"revokeLock success!!");
        NSArray<AgoraRtmLockDetail *> * lock_infos = response.lockDetailList;
        for (int i = 0 ; i < lock_infos.count; i++) {
            NSLog(@"lock name: %@, lock owner:%@, ttl: %d", lock_infos[i].lockName, lock_infos[i].owner, lock_infos[i].ttl);
        }

    } else {
        NSLog(@"revokeLock failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

removeLock

Description

If you no longer need a lock, you can call the removeLock method to remove the lock. After successfully removing the lock, all users in the channel receives the AgoraRtmLockEventTypeLockRemoved type of didReceiveLockEvent event notification. See Event Listeners.

Method

You can call the removeLock method as follows:

-(void) removeLock: (NSString * _Nonnull) channelName
       channelType: (AgoraRtmChannelType)channelType
          lockName: (NSString * _Nonnull) lockName
        completion: (AgoraRtmOperationBlock _Nullable)completionBlock;
ParametersTypeRequiredDefaultDescription
channelNameNSStringRequired-Channel name.
channelTypeAgoraRtmChannelTypeRequired-Channel types. See AgoraRtmChannelType.
lockNameNSStringRequired-Lock name.
completionBlockAgoraRtmOperationBlockOptional-Callback of invocation result:
- Success: Returns the AgoraRtmCommonResponse data in the response parameter, and nil in the errorInfo parameter.
- Failure: Returns nil in the response parameter, and error information in the errorInfo parameter.

Basic usage

[[rtm getLock] removeLock:@"my_channel" channelType:AgoraRtmChannelTypeStream lockName:@"my_lock" completion:^(AgoraRtmCommonResponse * _Nullable response, AgoraRtmErrorInfo * _Nullable errorInfo) {
    if (errorInfo == nil) {
        NSLog(@"removeLock success!!");
    } else {
        NSLog(@"removeLock failed, errorCode %d, reason %@", errorInfo.errorCode, errorInfo.reason);
    }
}];

Enumerated types

Enum

AgoraRtmAreaCode

The region for connection, which is the region where the server the SDK connects to is located.

ValueDescription
AgoraRtmAreaCodeCN0x00000001: Mainland China.
AgoraRtmAreaCodeNA0x00000002: North America.
AgoraRtmAreaCodeEU0x00000004: Europe.
AgoraRtmAreaCodeAS0x00000008: Asia, excluding Mainland China.
AgoraRtmAreaCodeJP0x00000010: Japan.
AgoraRtmAreaCodeIN0x00000020: India.
AgoraRtmAreaCodeGLOB0xFFFFFFFF: Global.

AgoraRtmChannelType

Channel types.

ValueDescription
AgoraRtmChannelTypeMessage1: Message channel.
AgoraRtmChannelTypeStream2: Stream channel.
AgoraRtmChannelTypeUser3: User Channel.

AgoraRtmClientConnectionChangeReason

Reasons causing the change of the connection state.

ValueDescription
AgoraRtmClientConnectionChangedConnecting0: The SDK is connecting with the server.
AgoraRtmClientConnectionChangedJoinSuccess1: The SDK has joined the channel successfully.
AgoraRtmClientConnectionChangedInterrupted2: The connection between the SDK and the server is interrupted.
AgoraRtmClientConnectionChangedBannedByServer3: The connection between the SDK and the server is banned by the server.
AgoraRtmClientConnectionChangedJoinFailed4: The SDK fails to join the channel. When the SDK fails to join the channel for more than 20 minutes, this error occurs and the SDK stops reconnecting to the channel.
AgoraRtmClientConnectionChangedLeaveChannel5: The SDK has left the channel.
AgoraRtmClientConnectionChangedInvalidAppId6: The connection failed because the App ID is not valid.
AgoraRtmClientConnectionChangedInvalidChannelName7: The connection failed because the channel name is not valid.
AgoraRtmClientConnectionChangedInvalidToken8: The connection failed because the token is not valid.
AgoraRtmClientConnectionChangedTokenExpired9: The connection failed because the token is expired.
AgoraRtmClientConnectionChangedRejectedByServer10: The connection is rejected by server.
AgoraRtmClientConnectionChangedSettingProxyServer11: The connection state changed to reconnecting because the SDK has set a proxy server.
AgoraRtmClientConnectionChangedRenewToken12: The connection state changed because the token is renewed.
AgoraRtmClientConnectionChangedClientIpAddressChanged13: The IP address of the client has changed, possibly because the network type, IP address, or port has been changed.
AgoraRtmClientConnectionChangedKeepAliveTimeout14: Timeout for the keep-alive of the connection between the SDK and the server. The connection state changes to reconnecting.
AgoraRtmClientConnectionChangedRejoinSuccess15: The user has rejoined the channel successfully.
AgoraRtmClientConnectionChangedChangedLost16: The connection between the SDK and the server is lost.
AgoraRtmClientConnectionChangedEchoTest17: The connection state changes due to the echo test.
AgoraRtmClientConnectionChangedClientIpAddressChangedByUser18: The local IP address was changed by the user. The connection state changes to reconnecting.
AgoraRtmClientConnectionChangedSameUidLogin19: The user joined the same channel from different devices with the same UID.
AgoraRtmClientConnectionChangedTooManyBroadcasters20: The number of hosts in the channel has reached the upper limit.
AgoraRtmClientConnectionChangedStreamChannelNotAvailable22: The stream channel does not exist.
AgoraRtmClientConnectionChangedLoginSuccess10001: The SDK logs in to the Signaling system.
AgoraRtmClientConnectionChangedLogout10002: The SDK logs out from the Signaling system.
AgoraRtmClientConnectionChangedPresenceNotReady10003: Presence service is not ready. You need to call the loginByToken method again to log in to the RTM system and re-execute all operations on the SDK.

AgoraRtmClientConnectionState

SDK connection states.

ValueDescription
AgoraRtmClientConnectionStateDisconnected1: The SDK has disconnected with the server.
AgoraRtmClientConnectionStateConnecting2: The SDK is connecting with the server.
AgoraRtmClientConnectionStateConnected3: The SDK has connected with the server.
AgoraRtmClientConnectionStateReconnecting4: The connection is lost. The SDK is reconnecting with the server.
AgoraRtmClientConnectionStateFailed5: The SDK failed to connect with the server.

AgoraRtmEncryptionMode

Encryption mode.

ValueDescription
AgoraRtmEncryptionNone0: No encryption.
AgoraRtmEncryptionAES128GCM1: AES-128-GCM mode.
AgoraRtmEncryptionAES256GCM2: AES-256-GCM mode.

AgoraRtmJoinChannelFeature

The event notification types set when joining a channel. You can use bitwise operations to set multiple event notifications simultaneously.

ValueDescription
AgoraRtmJoinChannelFeatureNone0: No event notifications.
AgoraRtmJoinChannelFeaturePresence1: Sets the presence event notification.
AgoraRtmJoinChannelFeatureMetadata1 &lt;&lt; 1: Sets the storage event notification.
AgoraRtmJoinChannelFeatureLock1 &lt;&lt; 2: Sets the lock event notification.
AgoraRtmJoinChannelFeatureBeQuiet1 &lt;&lt; 3: Sets the silent mode. In this mode, the SDK behaves as follows:
- You still receive event notifications from other users.
- Event notifications related to your channel activity, such as joining or leaving a channel, and actions related to setting, getting, or deleting temporary user states, are not broadcasted to other users.
- When calling the getOnlineUsers method, your information is not included.
- When calling the getUserChannels method, the channels that you subscribe to in silent mode are not included.

AgoraRtmLockEventType

Lock event type.

ValueDescription
AgoraRtmLockEventTypeSnapshot1: The snapshot of the lock when the user joined the channel.
AgoraRtmLockEventTypeLockSet2: The lock is set.
AgoraRtmLockEventTypeLockRemoved3: The lock is removed.
AgoraRtmLockEventTypeLockAcquired4: The lock is acquired.
AgoraRtmLockEventTypeLockReleased5: The lock is released.
AgoraRtmLockEventTypeLockExpired6: The lock expired.

AgoraRtmLogLevel

Log output levels.

ValueDescription
AgoraRtmLogLevelNone0x0000: No log.
AgoraRtmLogLevelInfo0x0001: Output the log at the FATAL, ERROR, WARN, or INFO level. We recommend you set to this value.
AgoraRtmLogLevelWarn0x0002: Output the log at the FATAL, ERROR, WARN level.
AgoraRtmLogLevelError0x0004: Output the log at the FATAL, ERROR level.
AgoraRtmLogLevelFatal0x0008: Output the log at the FATAL level.

AgoraRtmMessagePriority

Message priority.

ValueDescription
AgoraRtmMessagePriorityHighest0: Highest.
AgoraRtmMessagePriorityHigh1: High.
AgoraRtmMessagePriorityNormal4: Normal.
AgoraRtmMessagePriorityLow8: Low.

AgoraRtmMessageQos

QoS guarantee when sending topic messages.

ValueDescription
AgoraRtmMessageQosUnordered0: Message data is not guaranteed to arrive in order.
AgoraRtmMessageQosOrdered1: Message data arrives in order.

AgoraRtmPresenceEventType

Presence event type.

ValueDescription
AgoraRtmPresenceEventTypeSnapshot1: The snapshot of the presence when the user joined the channel.
AgoraRtmPresenceEventTypeInterval2: When users in the channel reach the setting value, the event notifications are sent at intervals rather than in real time.
AgoraRtmPresenceEventTypeRemoteJoinChannel3: A remote user joined the channel.
AgoraRtmPresenceEventTypeRemoteLeaveChannel4: A remote user left the channel.
AgoraRtmPresenceEventTypeRemoteConnectionTimeout5: A remote user's connection timed out.
AgoraRtmPresenceEventTypeRemoteStateChanged6: A remote user's temporary state changed.
AgoraRtmPresenceEventTypeErrorOutOfService7: The user did not enable presence when joining the channel.

AgoraRtmLinkOperation

Operation type.

ValueDescription
AgoraRtmLinkOperationLogin0: The user logins to the Signaling system.
AgoraRtmLinkOperationLogout1: The user logouts of the Signaling system.
AgoraRtmLinkOperationJoin2: The user joins in a stream channel.
AgoraRtmLinkOperationLeave3: The user leaves a stream channel.
AgoraRtmLinkOperationServerReject4: The Signaling server reject the connection.
AgoraRtmLinkOperationAutoReconnect5: The SDK is automatically reconnecting to the Signaling server.
AgoraRtmLinkOperationReconnected6: The SDK is reconnected to the Signaling server.
AgoraRtmLinkOperationHeartbeatTimeout7: The Signaling server does not receive the heartbeat packet within the specified timeout period.
AgoraRtmLinkOperationServerTimeout8: The Signaling server has timed out.
AgoraRtmLinkOperationNetworkChange9: The network status changes.

AgoraRtmLinkState

Link state type.

ValueDescription
AgoraRtmLinkStateIdle0: The init state.
AgoraRtmLinkStateConnecting1: Connecting.
AgoraRtmLinkStateConnected2: Connected.
AgoraRtmLinkStateDisconnected3: Disconnected.
AgoraRtmLinkStateSuspended4: Suspended.
AgoraRtmLinkStateFailed5: Failed.

AgoraRtmLinkStateChangeReason

Link state change reason.

ValueDescription
AgoraRtmLinkStateChangeReasonUnknown0: Unknown reason.
AgoraRtmLinkStateChangeReasonLogin1: Logging in.
AgoraRtmLinkStateChangeReasonLoginSuccess2: Login successful.
AgoraRtmLinkStateChangeReasonLoginTimeout3: Login timeout.
AgoraRtmLinkStateChangeReasonLoginNotAuthorized4: Login not authorized.
AgoraRtmLinkStateChangeReasonLoginRejected5: Login rejected.
AgoraRtmLinkStateChangeReasonRelogin6: Re-login.
AgoraRtmLinkStateChangeReasonLogout7: Logout.
AgoraRtmLinkStateChangeReasonAutoReconnect8: Auto-reconnect.
AgoraRtmLinkStateChangeReasonReconnectTimeout9: Reconnect timeout.
AgoraRtmLinkStateChangeReasonReconnectSuccess10: Reconnect successful.
AgoraRtmLinkStateChangeReasonJoin11: Joining a channel.
AgoraRtmLinkStateChangeReasonJoinSuccess12: Join channel successful.
AgoraRtmLinkStateChangeReasonJoinFailed13: Join channel failed.
AgoraRtmLinkStateChangeReasonRejoin14: Re-join a channel.
AgoraRtmLinkStateChangeReasonLeave15: Leave a channel.
AgoraRtmLinkStateChangeReasonInvalidToken16: Invalid token.
AgoraRtmLinkStateChangeReasonTokenExpired17: Token expired.
AgoraRtmLinkStateChangeReasonInconsistentAppId18: Inconsistent app ID.
AgoraRtmLinkStateChangeReasonInvalidChannelName19: Invalid channel name.
AgoraRtmLinkStateChangeReasonInvalidUserId20: Invalid user ID.
AgoraRtmLinkStateChangeReasonNotInitialized21: SDK not initialized.
AgoraRtmLinkStateChangeReasonRtmServiceNotConnected22: RTM service not connected.
AgoraRtmLinkStateChangeReasonChannelInstanceExceedLimitation23: Channel instance exceeds the limit.
AgoraRtmLinkStateChangeReasonOperationRateExceedLimitation24: Operation frequency exceeds the limit.
AgoraRtmLinkStateChangeReasonChannelInErrorState25: Channel in error state.
AgoraRtmLinkStateChangeReasonPresenceNotConnected26: Presence service not connected.
AgoraRtmLinkStateChangeReasonSameUidLogin27: Login with the same user ID.
AgoraRtmLinkStateChangeReasonKickedOutByServer28: Kicked out by the server.
AgoraRtmLinkStateChangeReasonKeepAliveTimeout29: Keepalive timeout.
AgoraRtmLinkStateChangeReasonConnectionError30: Connection error.
AgoraRtmLinkStateChangeReasonPresenceNotReady31: Presence service not ready.
AgoraRtmLinkStateChangeReasonNetworkChange32: Network changed.
AgoraRtmLinkStateChangeReasonServiceNotSupported33: Service not supported.
AgoraRtmLinkStateChangeReasonStreamChannelNotAvailable34: Stream Channel not available.
AgoraRtmLinkStateChangeReasonStorageNotAvailable35: Storage service not available.
AgoraRtmLinkStateChangeReasonLockNotAvailable36: Lock service not available.
AgoraRtmLinkStateChangeReasonLoginTooFrequent37: The login operation is too frequent.

AgoraRtmProtocolType

Protocol type.

ValueDescription
AgoraRtmProtocolTypeTcpUdp0: Both TCP and UDP protocols.
AgoraRtmProtocolTypeTcpOnly1: Only TCP protocol.

AgoraRtmServiceType

Service type

ValueDescription
AgoraRtmServiceTypeMessageThe foundational services comprise the message channel, user channel, presence, storage, and lock services.
AgoraRtmServiceTypeStreamThe stream channel service.

Information

To fully utilize all services offered by Signaling, use bitwise operations to simultaneously configure two service types.

AgoraRtmProxyType

Proxy type.

ValueDescription
AgoraRtmProxyTypeNone0: Do not enable the proxy.
AgoraRtmProxyTypeHttp1: Enable the proxy for the HTTP protocol.
AgoraRtmProxyTypeCloudTcp2: Enable cloud proxy for the TCP protocol.

AgoraRtmStorageEventType

Storage event type.

ValueDescription
AgoraRtmStorageEventTypeSnapshot1: When a user subscribes to channel metadata or user etadata for the first time, or joins a channel, the local user receives notifications of this type of event.
AgoraRtmStorageEventTypeSet2: Occurs when calling setChannelMetadata or setUserMetadata. Caution: This event only occurs in incremental data update mode.
AgoraRtmStorageEventTypeUpdate3: Occurs when calling methods to set, update, or delete the channel metadata or user metadata.
AgoraRtmStorageEventTypeRemove4: Occurs when calling removeChannelMetadata or removeUserMetadata. Caution: This event only occurs in incremental data update mode.

AgoraRtmStorageType

Storage type.

ValueDescription
AgoraRtmStorageTypeUser1: User metadata event.
AgoraRtmStorageTypeChannel2: Channel metadata event.

AgoraRtmSubscribeChannelFeature

The event notification types set when subscribing to a channel. You can use bitwise operations to set multiple event notifications simultaneously.

ValueDescription
AgoraRtmSubscribeChannelFeatureNone0: No event notifications
AgoraRtmSubscribeChannelFeaturePresence1: Sets the presence event notification.
AgoraRtmSubscribeChannelFeatureMetadata1 &lt;&lt; 1: Sets the storage event notification.
AgoraRtmSubscribeChannelFeatureMessage1 &lt;&lt; 2: Sets the message event notification.
AgoraRtmSubscribeChannelFeatureLock1 &lt;&lt; 3: Sets the lock event notification.
AgoraRtmSubscribeChannelFeatureBeQuiet1 &lt;&lt; 4: Sets the silent mode. In this mode, the SDK behaves as follows:
- You still receive event notifications from other users.
- Event notifications related to your channel activity, such as joining or leaving a channel, and actions related to setting, getting, or deleting temporary user states, are not broadcasted to other users.
- When calling the getOnlineUsers method, your information is not included.
- When calling the getUserChannels method, the channels that you subscribe to in silent mode are not included.

AgoraRtmTopicEventType

Topic event type.

ValueDescription
AgoraRtmTopicEventTypeSnapshot1: The snapshot of the topic when the user joined the channel.
AgoraRtmTopicEventTypeRemoteJoinTopic2: A remote user joined the channel.
AgoraRtmTopicEventTypeRemoteLeaveTopic3: A remote user left the channel.

Troubleshooting

Refer to the following information for troubleshooting API calls.

ErrorInfo

PropertiesTypeDescription
errorCodeAgoraRtmErrorCodeError code for this operation.
reasonNSStringError reason for this operation.
operationNSStringOperation type.

To find out the cause of the error and get the corresponding solution, use the errorCode field with the error codes table.

Error codes table

Refer to the following error codes table to identify and troubleshoot the problem:

Error codeError descriptionCause and solution
0AgoraRtmErrorOkCorrect call
-10001AgoraRtmErrorNotInitializedThe SDK is not initialized. Please initialize the RtmClient instance by calling the initWithConfig method before performing other operations.
-10002AgoraRtmErrorNotLoginThe user called the API without logging in to Signaling, disconnected due to timeout, or actively logged out. Please log in to Signaling first.
-10003AgoraRtmErrorInvalidAppIdInvalid App ID:
- Check that the App ID is correct.
- Ensure that Signaling has been activated for the App ID.
-10005AgoraRtmErrorInvalidTokenInvalid Token:
- The token is invalid, check whether the Token Provider generates a valid Signaling Token.
-10006AgoraRtmErrorInvalidUserIdInvalid User ID:
- Check if user ID is empty.
- Check if the user ID contains illegal characters.
-10007AgoraRtmErrorInitServiceFailedSDK initialization failed. Please reinitialize by calling the initWithConfig method.
-10008AgoraRtmErrorInvalidChannelNameInvalid channel name:
- Check if the channel name is empty.
- Check if the channel name contains illegal characters.
-10009AgoraRtmErrorTokenExpiredToken expired. Call renewToken to reacquire the Token.
-10010AgoraRtmErrorLoginNoServerResourcesServer resources are limited. It is recommended to log in again.
-10011AgoraRtmErrorLoginTimeoutLogin timeout. Check whether the current network is stable and switch to a stable network environment.
-10012AgoraRtmErrorLoginRejectedSDK login rejected by the server:
- Check tha Signaling is activated on your App ID.
- Check if the token or userId is banned.
-10013AgoraRtmErrorLoginAbortedSDK login interrupted due to unknown problem:
- Check that the current network is stable and switch to a stable network environment.
- The current userId is logged in.
-10014AgoraRtmErrorInvalidParameterInvalid parameter. Please check if the parameters you provided are correct.
-10015AgoraRtmErrorLoginNotAuthorizedNo RTM service permissions. Check that the console opens Signaling services.
-10016AgoraRtmErrorLoginInconsistentAppIdInconsistent App ID. Please check whether the App ID used for initialization, login, and joining a channel are consistent.
-10017AgoraRtmErrorDuplicateOperationDuplicate operation.
-10018AgoraRtmErrorInstanceAlreadyReleasedRepeat rtm instantiation or RTMStreamChannel instantiation.
-10019AgoraRtmErrorInvalidChannelTypeInvalid channel type. The SDK only supports the following channel types. Please use the correct value:
- AgoraRtmChannelTypeMessage: Message Channel
- AgoraRtmChannelTypeStream: Stream Channel
- AgoraRtmChannelTypeUser: User Channel
-10020AgoraRtmErrorInvalidEncryptionParameterMessage encryption parameters are invalid.
- Check that the encryption key generated is a String.
- Check that the generated encryption salt is Uint8Array type and that the length is 32 bytes.
- Check that the encryption method matches the encryption key and the encryption salt.
-10021AgoraRtmErrorOperationRateExceedLimitationChannel metadata or User Metadata -related API call frequency is exceeding the limit. Please control the call frequency within 10/second.
-10022AgoraRtmErrorServiceNotSupportThe service type is not supported. Check whether the service type you set in AgoraRtmServiceType is correct. This error code is only applicable to the private deployment function.
-10023AgoraRtmErrorLoginCanceledThe login operation has been canceled. Possible reasons are as follows:
- After calling the loginByToken method, if you call the method again before receiving the call result, the previous call operation will be canceled and the SDK will execute the next call.
- Calling the logout method to log out before successfully logging in.
-10024AgoraRtmErrorInvalidPrivateConfigThe private deployment parameter settings are invalid. Please check whether the service type and server address you set in AgoraRtmPrivateConfig are valid.
-10025AgoraRtmErrorNotConnectedNot connected to the Signaling server. When you call APIs related to message subscription, metadata, or the Lock module, this error is reported if the Signaling service is not connected.
-10026AgoraRtmErrorRenewTokenTimeoutToken renewal timed out.
-11001AgoraRtmErrorChannelNotJoinedThe user has not joined the channel:
- The user is not online, offline or has not joined the channel
- Check for typos in userId.
-11002AgoraRtmErrorChannelNotSubscribedThe user has not subscribed to the channel:
- The user is not online, offline or has not joined the channel
- Check for typos in userId.
-11003AgoraRtmErrorChannelExceedTopicUserLimitationThe number of subscribers to this topic exceeds the limit.
-11004AgoraRtmErrorChannelReusedIn co-channel mode, RTM released the Stream Channel.
-11005AgoraRtmErrorChannelInstanceExceedLimitationThe number of created or subscribed channels exceeds the limit. See API usage limits for details.
-11006AgoraRtmErrorChannelInErrorStateChannel is not available. Please recreate the Stream Channel or resubscribe to the Message Channel.
-11007AgoraRtmErrorChannelJoinFailedFailed to join this channel:
- Check if the number of joined channels exceeds the limit.
- Check if the channel name is illegal.
- Check if the network is disconnected.
-11008AgoraRtmErrorChannelInvalidTopicNameInvalid topic name:
- Check whether the topic name contains illegal characters.
- Check if the topic name is empty.
-11009AgoraRtmErrorChannelInvalidMessageInvalid message. Check whether the message type is legal, Signaling only supports string, Uint8Array type messages.
-11010AgoraRtmErrorChannelMessageLengthExceedLimitationMessage length exceeded limit. Check if the message payload size exceeds the limit:
- Message Channel single message package limit is 32 KB.
- Stream Channel single message package limit is 1 KB.
-11011AgoraRtmErrorChannelInvalidUserListInvalid user list:
- Check if the user list is empty.
- Check if the user list contains invalid entries.
-11012AgoraRtmErrorChannelNotAvailableInvalid user list:
- Check if the user list is empty
- Check if the user list contains illegal items.
-11013AgoraRtmErrorChannelTopicNotSubscribedThe topic is not subscribed.
-11014AgoraRtmErrorChannelExceedTopicLimitationThe number of topics exceeds the limit.
-11015AgoraRtmErrorChannelJoinTopicFailedFailed to join this topic. Check whether the number of added topics exceeds the limit.
-11016AgoraRtmErrorChannelTopicNotJoinedThe topic has not been joined. To send a message, you need to join the Topic first.
-11017AgoraRtmErrorChannelTopicNotExistThe topic does not exist. Check that the topic name is correct.
-11018AgoraRtmErrorChannelInvalidTopicMetaThe meta parameters in the topic are invalid. Check if the meta parameter exceeds 256 bytes.
-11019AgoraRtmErrorChannelSubscribeTimeoutChannel subscription timed out. Check for broken connections.
-11020AgoraRtmErrorChannelSubscribeTooFrequentThe channel subscription operation is too frequent. Make sure that the subscription operation of the same channel within a 5 seconds interval does not exceed 2 attempts.
-11021AgoraRtmErrorChannelSubscribeFailedChannel subscription failed.11003 Check if the number of subscribed channels exceeds the limit.
-11022AgoraRtmErrorChannelUnsubscribeFailedFailed to unsubscribe from the channel. Check if the connection is disconnected.
-11023AgoraRtmErrorChannelEncryptMessageFailedMessage encryption failed:
- Check that the cipherKey is valid.
- Check that the salt is valid.
- Check if encryptionMode mode matches the cipherKey and salt.
-11024AgoraRtmErrorChannelPublishMessageFailedMessage publishing failed. Check for broken connections.
-11026AgoraRtmErrorChannelPublishMessageTimeoutMessage publishing timed out. Check for broken connections.
-11027AgoraRtmErrorChannelNotConnectedThe SDK is disconnected from the Signaling server. Please log in again.
-11028AgoraRtmErrorChannelLeaveFailedFailed to leave the channel. Check for broken connections.
-11029AgoraRtmErrorChannelCustomTypeLengthOverflowCustom type length overflow. The length of the customType field must to be within 32 characters.
-11030AgoraRtmErrorChannelInvalidCustomTypecustomType field is invalid. Check the customType field for illegal characters.
-11031AgoraRtmErrorChannelUnsupportedMessageTypeMessage type is not supported.
-11032AgoraRtmErrorChannelPresenceNotReadyPresence service is not ready. Please rejoin the Stream Channel or resubscribe to the Message Channel.
-11033AgoraRtmErrorChannelReceiverOfflineWhen sending a user message, the remote user is offline:
- Check if the user ID set when calling the method is correct.
- Check if the remote user is logged in and online.
-11034AgoraRtmErrorChannelJoinCanceledThe join channel operation has been canceled. After calling the joinTopic method, if you call the method again before receiving the call result, the previous call operation will be canceled and the SDK will execute the next call.
-12001AgoraRtmErrorStorageOperationFailedStorage operation failed.
-12002AgoraRtmErrorStorageMetadataItemExceedLimitationThe number of Storage Metadata Items exceeds the limit.
-12003AgoraRtmErrorStorageInvalidMetadataItemInvalid Metadata Item.
-12004AgoraRtmErrorStorageInvalidArgumentInvalid argument.
-12005AgoraRtmErrorStorageInvalidRevisionInvalid Revision parameter.
-12006AgoraRtmErrorStorageMetadataLengthOverflowMetadata overflows.
-12007AgoraRtmErrorStorageInvalidLockNameInvalid Lock name.
-12008AgoraRtmErrorStorageLockNotAcquiredThe Lock was not acquired.
-12009AgoraRtmErrorStorageInvalidKeyInvalid Metadata key.
-12010AgoraRtmErrorStorageInvalidValueInvalid metadata value.
-12011AgoraRtmErrorStorageKeyLengthOverflowMetadata key length overflow.
-12012AgoraRtmErrorStorageValueLengthOverflowMetadata value length overflow.
-12013AgoraRtmErrorStorageDuplicateKeyDuplicate Metadata Item key.
-12014AgoraRtmErrorStorageOutdatedRevisionOutdated Revision parameter.
-12015AgoraRtmErrorStorageNotSubscribeThis channel is not subscribed.
-12016AgoraRtmErrorStorageInvalidMetadataInstanceMetadata instance does not exist. Please create a Metadata instance.
-12017AgoraRtmErrorStorageSubscribeUserExceedLimitationThe number of subscribers exceeds the limit.
-12018AgoraRtmErrorStorageOperationTimeoutStorage operation timed out.
-12019AgoraRtmErrorStorageNotAvailableThe Storage service is not available.
-13001AgoraRtmErrorPresenceNotConnectedThe user is not connected to the system.
-13002AgoraRtmErrorPresenceNotWritablePresence service is unavailable.
-13003AgoraRtmErrorPresenceInvalidArgumentInvalid argument.
-13004AgoraRtmErrorPresenceCacheTooManyStatesThe temporary user state cached before joining the channel exceeds the limit. See API usage limits for details.
-13005AgoraRtmErrorPresenceStateCountOverflowThe number of temporary user state key/value pairs exceeds the limit. See API usage limits for details.
-13006AgoraRtmErrorPresenceInvalidStateKeyInvalid state key.
-13007AgoraRtmErrorPresenceInvalidStateValueInvalid state value.
-13008AgoraRtmErrorPresenceStateKeySizeOverflowPresence key length overflow.
-13009AgoraRtmErrorPresenceStateValueSizeOverflowPresence value overflow
-13010AgoraRtmErrorPresenceStateDuplicateKeyRepeated state key.
-13011AgoraRtmErrorPresenceUserNotExistThe user does not exist.
-13012AgoraRtmErrorPresenceOperationTimeoutPresence operation timed out.
-13013AgoraRtmErrorPresenceOperationFailedPresence operation failed.
-14001AgoraRtmErrorLockOperationFailedLock operation failed.
-14002AgoraRtmErrorLockOperationTimeoutLock operation timed out.
-14003AgoraRtmErrorLockOperationPerformingLock operation in progress.
-14004AgoraRtmErrorLockAlreadyExistLock already exists.
-14005AgoraRtmErrorLockInvalidNameInvalid Lock name.
-14006AgoraRtmErrorLockNotAcquiredThe Lock was not acquired.
-14007AgoraRtmErrorLockAcquireFailedFailed to acquire the Lock.
-14008AgoraRtmErrorLockNotExistThe Lock does not exist.
-14009AgoraRtmErrorLockNotAvailableLock service is not available.