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
- User authentication
- Channels
- Topics
- Messages
- Presence
- Storage
- Lock
- Enumerated types
- Troubleshooting
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| Methods | Description |
|---|---|
init | Prevents users from initializing the AgoraRtmClientConfig instance without providing the required parameters. |
initWithAppId | Requires users to provide the appId and userId parameters during initializing the AgoraRtmClientConfig instance. |
| Properties | Type | Required | Default | Description |
|---|---|---|---|---|
appId | NSString | Required | - | App ID obtained when creating a project in the Agora Console. |
userId | NSString | Required | - | 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. |
areaCode | AgoraRtmAreaCode | Optional | AgoraRtmAreaCodeGLOB | Service area code, you can choose according to the region where your business is deployed. See AgoraRtmAreaCode. |
protocolType | AgoraRtmProtocolType | Optional | AgoraRtmProtocolTypeTcpUdp | Protocol 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. |
presenceTimeout | unsigned int | Optional | 300 | Presence 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. |
heartbeatInterval | unsigned int | Optional | 5 | Heartbeat 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. |
reconnectTimeout | uint32_t | Optional | 0 | SDK 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. |
useStringUserId | BOOL | Optional | true | Whether 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. |
ispPolicyEnabled | Bool | Optional | false | Whether 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. |
logConfig | AgoraRtmLogConfig | Optional | - | Log configuration properties such as the log storage size, storage path, and level. |
proxyConfig | AgoraRtmProxyConfig | Optional | - | When using the Proxy feature of Signaling, you need to configure this parameter. |
encryptionConfig | AgoraRtmEncryptionConfig | Optional | - | When using the client-side encryption feature of Signaling, you need to configure this parameter. |
privateConfig | AgoraRtmPrivateConfig | Optional | - | 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:
| Properties | Type | Required | Default | Description |
|---|---|---|---|---|
filePath | NSString | Optional | - | Log file storage paths. |
fileSizeInKB | int | Optional | 1024 | Log 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. |
level | AgoraRtmLogLevel | Optional | AgoraRtmLogLevelInfo | Output 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:
| Methods | Description |
|---|---|
init | Prevents users from initializing the AgoraRtmProxyConfig instance without providing the required parameters. |
initWithServer | Requires users to provide the server, port, and proxyType parameters during initializing the AgoraRtmProxyConfig instance. |
| Properties | Type | Required | Default | Description |
|---|---|---|---|---|
proxyType | AgoraRtmProxyType | Optional | AgoraRtmProxyTypeNone | Proxy protocol type. See AgoraRtmProxyType. |
server | NSString | Required | - | Proxy server domain name or IP address. |
port | unsigned short | Optional | - | Proxy listening port. |
account | NSString | Optional | - | Proxy login account. |
password | NSString | Optional | - | 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:
| Properties | Type | Required | Default | Description |
|---|---|---|---|---|
encryptionMode | AgoraRtmEncryptionMode | Optional | AgoraRtmEncryptionNone | Encryption mode. See AgoraRtmEncryptionMode. |
encryptionKey | NSString | Optional | - | User-defined encryption key, unlimited length. Agora recommends using a 32-byte key. |
encryptionKdfSalt | NSData | Optional | - | 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:
| Properties | Type | Required | Default | Description |
|---|---|---|---|---|
serviceType | EnumSet<RtmServiceType> | Optional | - | Service type. See AgoraRtmServiceType. |
accessPointHosts | NSArray<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:));| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
config | AgoraRtmClientConfig | Required | - | Initialize the configuration parameters of the Signaling Client. See AgoraRtmClientConfig. |
delegate | id <AgoraRtmClientDelegate> | Optional | - | Signaling event notification listener settings. See Event listeners. |
error | NSError | Required | - | (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 Type | Description |
|---|---|
didReceiveMessageEvent | Receive message notifications from all subscribed Message Channels or topic message notifications subscribed to, in all Stream Channels you join. See AgoraRtmMessageEvent . |
didReceivePresenceEvent | Receive presence event notifications in subscribed message channels and joined stream channels. See AgoraRtmPresenceEvent |
didReceiveTopicEvent | Receive all topic event notifications in joined stream channels. See AgoraRtmTopicEvent |
didReceiveStorageEvent | Receive channel metadata event notifications in subscribed message channels and joined stream channels, and the user metadata event notification of the subscribed users. See AgoraRtmStorageEvent |
didReceiveLockEvent | Receive 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. |
didReceiveLinkStateEvent | Receive event notifications when client connection status changes. See AgoraRtmLinkStateEvent. |
tokenPrivilegeWillExpire | Receive 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
addDelegatemethod.
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:
| Properties | Type | Description |
|---|---|---|
channelType | AgoraRtmChannelType | Channel types. See AgoraRtmChannelType. |
channelName | NSString | Channel name. |
channelTopic | NSString | Topic name. |
message | AgoraRtmMessage | Message. |
publisher | NSString | User ID of the message publisher. |
customType | NSString | A user-defined field. Only supports NSString type. |
timestamp | unsigned long long | The timestamp when the event occurs. |
AgoraRtmMessage contains the following properties:
| Properties | Type | Description |
|---|---|---|
rawData | NSData | Binary message. |
stringData | NSString | String message. |
AgoraRtmPresenceEvent
User presence event.
AgoraRtmPresenceEvent contains the following properties:
| Properties | Type | Description |
|---|---|---|
type | AgoraRtmPresenceEventType | Presence event type. See AgoraRtmPresenceEventType. |
channelType | AgoraRtmChannelType | Channel types. See AgoraRtmChannelType. |
channelName | NSString | Channel name. |
publisher | NSString | User ID of the message publisher. |
states | NSDictionary | Key-value pair that identifies the user's presence state. |
interval | AgoraRtmPresenceIntervalInfo | In 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. |
snapshot | NSArray<AgoraRtmUserState *> | 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. |
timestamp | unsigned long long | The timestamp when the event occurs. |
The AgoraRtmPresenceIntervalInfo data type contains the following properties:
| Properties | Type | Description |
|---|---|---|
joinUserList | NSArray<NSString *> | List of users who joined the channel in the previous cycle. |
leaveUserList | NSArray<NSString *> | List of users who left the channel in the previous cycle. |
timeoutUserList | NSArray<NSString *> | List of users who timed out joining the channel in the previous cycle. |
userStateList | ArrayList<UserState> | 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:
| Properties | Type | Description |
|---|---|---|
userId | NSString | User ID. |
states | NSDictionary | List of online users and their temporary state information in a specified channel. |
AgoraRtmStateItem data type contains the following properties:
| Properties | Type | Description |
|---|---|---|
key | NSString | Key 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. |
value | NSString | Value of the user state. |
AgoraRtmTopicEvent
Topic event.
AgoraRtmTopicEvent contains the following properties:
| Properties | Type | Description |
|---|---|---|
type | AgoraRtmTopicEventType | Topic event type. See AgoraRtmTopicEventType. |
channelName | NSString | Channel name. |
publisher | NSString | User ID. |
topicInfos | NSArray<AgoraRtmTopicInfo *> | Topic information. |
timestamp | unsigned long long | The timestamp when the event occurs. |
The AgoraRtmTopicInfo data type contains the following properties:
| Properties | Type | Description |
|---|---|---|
topic | NSString | Topic name. |
publishers | NSArray<AgoraRtmPublisherInfo *> | Message publisher array. |
The AgoraRtmPublisherInfo data type contains the following properties:
| Properties | Type | Description |
|---|---|---|
publisherUserId | NSString | User ID of the message publisher. |
publisherMeta | NSString | Metadata of the message publisher. |
AgoraRtmStorageEvent
Storage event.
AgoraRtmStorageEvent contains the following properties:
| Properties | Type | Description |
|---|---|---|
channelType | AgoraRtmChannelType | Channel types. See AgoraRtmChannelType. |
storageType | AgoraRtmStorageType | Storage type. See AgoraRtmStorageType. |
eventType | AgoraRtmStorageEventType | Storage event type. See AgoraRtmStorageEventType. |
target | NSString | User ID or channel name. |
data | AgoraRtmMetadata | Metadata item. See AgoraRtmMetadata. |
timestamp | unsigned long long | The timestamp when the event occurs. |
AgoraRtmLockEvent
Lock event.
AgoraRtmLockEvent contains the following properties:
| Properties | Type | Description |
|---|---|---|
channelType | AgoraRtmChannelType | Channel types. See AgoraRtmChannelType. |
eventType | AgoraRtmLockEventType | Lock event type. See AgoraRtmLockEventType. |
channelName | NSString | Channel name. |
lockDetailList | ArrayList<LockDetail> | Details of lock. |
timestamp | unsigned long long | The timestamp when the event occurs. |
The AgoraRtmLockDetail data type contains the following properties:
| Properties | Type | Description |
|---|---|---|
lockName | NSString | Lock name. |
owner | NSString | The ID of the user who has a lock. |
ttl | int | The 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:
| Parameters | Type | Description |
|---|---|---|
currentState | AgoraRtmLinkState | The current link state. See AgoraRtmLinkState. |
previousState | AgoraRtmLinkState | The previous link state. See AgoraRtmLinkState. |
serviceType | AgoraRtmServiceType | The network connection type. See AgoraRtmServiceType. |
operation | AgoraRtmLinkOperation | The operation that triggered the current state transition. See AgoraRtmLinkOperation. |
reasonCode | AgoraRtmLinkStateChangeReason | The reason for this state transition. See AgoraRtmLinkStateChangeReason. |
reason | NSString | The reason for the current state transition. This parameter will be deprecated in the future, please use the reasonCode parameter instead. |
affectedChannels | NSArray<NSString *> | The channels affected by the current state transition. |
unrestoredChannels | NSArray<NSString *> | 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. |
isResumed | BOOL | Within 2 minutes of the disconnection, whether the state transitions from AgoraRtmLinkStateDisconnected to AgoraRtmLinkStateConnected. true refers to the state has transitioned. |
timestamp | unsigned long long | The 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;| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
token | NSString | Optional | - | 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. |
completionBlock | AgoraRtmOperationBlock | Optional | - | 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
responseparameter, and thenilin theerrorInfoparameter. - Failure: Returns
nilin theresponseparameter, and error information in theerrorInfoparameter.
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:
| Properties | Type | Description |
|---|---|---|
errorCode | AgoraRtmErrorCode | Error code for this operation. |
reason | NSString | Error reason for this operation. |
operation | NSString | Operation 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;| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
completionBlock | AgoraRtmOperationBlock | Optional | - | 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
loginByTokenmethod, 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
joinTopicmethod, 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:));| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
token | string | Required | - | The newly generated Signaling token. |
completionBlock | AgoraRtmOperationBlock | Optional | - | 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:));| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
token | string | Required | - | The newly generated RTC token. |
completionBlock | AgoraRtmOperationBlock | Optional | - | 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
didReceiveMessageEventevents. -
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;| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | NSString | Required | - | Channel name. |
subscribeOption | AgoraRtmSubscribeOptions | Optional | - | Options for subscribing to a channel. |
completionBlock | AgoraRtmOperationBlock | Optional | - | 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:
| Properties | Type | Required | Default | Description |
|---|---|---|---|---|
features | AgoraRtmSubscribeChannelFeature | Optional | AgoraRtmSubscribeChannelFeatureMessage and AgoraRtmSubscribeChannelFeaturePresence | Sets 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;| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | NSString | Required | - | Channel name. |
completionBlock | AgoraRtmOperationBlock | Optional | - | 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(_:));| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | NSString | Required | - | Channel name. |
error | NSError | Required | - | (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
AgoraRtmStreamChannelto 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
AgoraRtmPresenceEventTypeSnapshottype of thedidReceivePresenceEventevent. - The
AgoraRtmTopicEventTypeSnapshottype of thedidReceiveTopicEventevent.
- The
- For remote users: The
AgoraRtmPresenceEventTypeRemoteJoinChanneltype of thedidReceivePresenceEventevent.
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;| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
option | AgoraRtmJoinChannelOption | Required | - | Options for joining a channel. |
completionBlock | AgoraRtmOperationBlock | Optional | - | 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:
| Properties | Type | Required | Default | Description |
|---|---|---|---|---|
token | NSString | Optional | - | 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. |
features | AgoraRtmJoinChannelFeature | Optional | AgoraRtmJoinChannelFeaturePresence | Sets 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;| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
completionBlock | AgoraRtmOperationBlock | Optional | - | 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
AgoraRtmStreamChannelinstance and call thejoinTopicmethod 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| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
topic | NSString | Required | - | Topic name. |
option | AgoraRtmJoinTopicOption | Optional | - | Options for joining a topic. |
completionBlock | AgoraRtmOperationBlock | Optional | - | 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:
| Properties | Type | Required | Default | Description |
|---|---|---|---|---|
qos | AgoraRtmMessageQos | Optional | AgoraRtmMessageQosUnordered | Whether the data transmitted in the topic is ordered. See AgoraRtmMessageQos. |
priority | AgoraRtmMessagePriority | Optional | AgoraRtmMessagePriorityNormal | The priority of data transmission in the topic compared to other topics in the same channel. See AgoraRtmMessagePriority. |
meta | NSString | Optional | - | Adds additional metadata when joining the topic. |
syncWithMedia | BOOL | Optional | false | Whether 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| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
topic | NSString | Required | - | Topic name. |
message | NSString | Required | - | Sends string messages in the publishTopicMessage[1/2] method. |
data | NSData | Required | - | Sends binary messages in the publishTopicMessage[2/2] method. |
options | AgoraRtmTopicMessageOptions | Optional | - | Message options. |
completionBlock | AgoraRtmOperationBlock | Optional | - | 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:
| Properties | Type | Required | Default | Description |
|---|---|---|---|---|
sendTs | unsigned long long | Optional | 0 | The 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. |
customType | NSString | Required | - | 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;| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
topic | NSString | Required | - | Topic name. |
completionBlock | AgoraRtmOperationBlock | Optional | - | 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| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
topic | NSString | Required | - | Topic name. |
option | AgoraRtmTopicOption | Optional | - | Options for subscribing to a topic. |
completionBlock | AgoraRtmTopicSubscriptionBlock | Optional | - | 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:
| Properties | Type | Required | Default | Description |
|---|---|---|---|---|
users | NSArray<NSString *> | 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:
| Properties | Type | Description |
|---|---|---|
succeedUsers | NSArray<NSString *> | A list of successfully subscribed users. |
failedUsers | NSArray<NSString *> | 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| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
topic | NSString | Required | - | Topic name. |
options | AgoraRtmTopicOption | Optional | - | Options for unsubscribe from a topic. |
completionBlock | AgoraRtmOperationBlock | Optional | - | 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:
| Properties | Type | Required | Default | Description |
|---|---|---|---|---|
users | NSArray<NSString *> | 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
publishTopicMessagemethod, set thechannelTypeparameter toAgoraRtmChannelTypeMessage, and set thechannelNameparameter to the channel name to send messages in the channel. The remote users can call thesubscribeTopicmethod 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
publishTopicMessagemethod, set thechannelTypeparameter toAgoraRtmChannelTypeUser, and set thechannelNameparameter to the user ID to send messages to the specified user. The specified remote users receive messages through thedidReceiveMessageEventevent 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
publishTopicMessagemethod to send messages in the topic, and remote users can call thesubscribeTopicmethod 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| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | NSString | Required | - | 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. |
message | NSString | Required | - | Sends string messages in the publishTopicMessage[1/2] method. |
data | NSData | Required | - | Sends binary messages in the publishTopicMessage[2/2] method. |
publishOption | AgoraRtmTopicMessageOptions | Optional | - | Message options. |
completionBlock | AgoraRtmOperationBlock | Optional | - | 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:
| Properties | Type | Required | Default | Description |
|---|---|---|---|---|
channelType | AgoraRtmChannelType | Required | - | Channel types. See AgoraRtmChannelType. |
customType | NSString | Required | - | 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;| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | NSString | Required | - | Channel name. |
channelType | AgoraRtmChannelType | Required | - | Channel types. See AgoraRtmChannelType. |
options | AgoraRtmGetOnlineUsersOptions | Optional | - | Query options. |
completionBlock | AgoraRtmGetOnlineUsersBlock | Optional | - | 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:
| Properties | Type | Required | Default | Description |
|---|---|---|---|---|
includeUserId | BOOL | Optional | true | Whether the returned result includes the user ID of online members. |
includeState | BOOL | Optional | false | Whether the returned result includes temporary state data of online users. |
page | NSString | Required | - | 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:
| Properties | Type | Description |
|---|---|---|
totalOccupancy | int | The 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. |
userStateList | NSArray<AgoraRtmUserState *> | List of online users and their temporary state information in a specified channel. |
nextPage | NSString | Page 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:
| Properties | Type | Description |
|---|---|---|
userId | NSString | User ID. |
states | NSDictionary | List of online users and their temporary state information in a specified channel. |
AgoraRtmStateItem data type contains the following properties:
| Properties | Type | Description |
|---|---|---|
key | NSString | Key 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. |
value | NSString | Value 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;| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
userId | NSString | Required | - | User ID. |
completionBlock | AgoraRtmGetUserChannelsBlock | Optional | - | 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:
| Properties | Type | Description |
|---|---|---|
totalChannel | int | Number of channels the user is in. |
channels | NSArray<AgoraRtmChannelInfo *> | List of channel information, including channel name and channel type. |
The AgoraRtmChannelInfo data type contains the following properties:
| Properties | Type | Description |
|---|---|---|
channelName | NSString | Channel name. |
channelType | AgoraRtmChannelType | Channel 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;| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | NSString | Required | - | Channel name |
channelType | AgoraRtmChannelType | Required | - | Channel types. See AgoraRtmChannelType. |
items | NSDictionary | Required | - | User state, an array of StateItem. |
completionBlock | AgoraRtmOperationBlock | Optional | - | 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;| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | NSString | Required | - | Channel name. |
channelType | AgoraRtmChannelType | Required | - | Channel types. See AgoraRtmChannelType. |
userId | NSString | Required | - | User ID. |
completionBlock | AgoraRtmPresenceGetStateBlock | Optional | - | 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:
| Properties | Type | Description |
|---|---|---|
state | AgoraRtmUserState | List of online users and their temporary state information in a specified channel. |
The AgoraRtmUserState data type contains the following properties:
| Properties | Type | Description |
|---|---|---|
userId | NSString | User ID. |
states | NSDictionary | List of online users and their temporary state information in a specified channel. |
AgoraRtmStateItem data type contains the following properties:
| Properties | Type | Description |
|---|---|---|
key | NSString | Key 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. |
value | NSString | Value 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| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | NSString | Required | - | Channel name |
channelType | AgoraRtmChannelType | Required | - | Channel types. See AgoraRtmChannelType. |
keys | NSArray<NSString *> | Required | - | List of keys to be deleted. If you do not provide this property, the SDK removes all states. |
completionBlock | AgoraRtmOperationBlock | Optional | - | 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, thevalueof 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
majorRevisionproperty in theAgoraRtmMetadatadata type. - Enable version number verification for a single metadata item by setting the
revisionproperty in theAgoraRtmMetadataItemclass.
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;| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | NSString | Required | - | Channel name. |
channelType | AgoraRtmChannelType | Required | - | Channel types. See AgoraRtmChannelType. |
data | AgoraRtmMetadata | Required | - | Metadata item. See AgoraRtmMetadata. |
options | AgoraRtmMetadataOptions | Optional | - | Options for setting the channel metadata. |
lock | NSString | Optional | nil string '' | Lock name. If set, only users who call the acquireLock method to acquire the lock can perform operations. |
completionBlock | AgoraRtmOperationBlock | Optional | - | 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:
| Properties | Type | Required | Default | Description |
|---|---|---|---|---|
recordTs | BOOL | Optional | false | Whether to record the timestamp of the edits. |
recordUserId | BOOL | Optional | false | Whether 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;| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | NSString | Required | - | Channel name. |
channelType | AgoraRtmChannelType | Required | - | Channel types. See AgoraRtmChannelType. |
completionBlock | AgoraRtmGetMetadataBlock | Optional | - | 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:
| Properties | Type | Description |
|---|---|---|
data | AgoraRtmMetadata | Metadata 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;| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | NSString | Required | - | Channel name. |
channelType | AgoraRtmChannelType | Required | - | Channel types. See AgoraRtmChannelType. |
data | AgoraRtmMetadata | Required | - | Metadata item. See AgoraRtmMetadata. |
options | AgoraRtmMetadataOptions | Optional | - | Options for setting the channel metadata. |
lock | NSString | Optional | nil string '' | Lock name. If set, only users who call the acquireLock method to acquire the lock can perform operations. |
completionBlock | AgoraRtmOperationBlock | Optional | - | 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:
| Properties | Type | Required | Default | Description |
|---|---|---|---|---|
recordTs | BOOL | Optional | false | Whether to record the timestamp of the edits. |
recordUserId | BOOL | Optional | false | Whether 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;| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | NSString | Required | - | Channel name. |
channelType | AgoraRtmChannelType | Required | - | Channel types. See AgoraRtmChannelType. |
data | AgoraRtmMetadata | Required | - | Metadata item. See AgoraRtmMetadata. |
options | AgoraRtmMetadataOptions | Optional | - | Options for setting the channel metadata. |
lock | NSString | Optional | nil string '' | Lock name. If set, only users who call the acquireLock method to acquire the lock can perform operations. |
completionBlock | AgoraRtmOperationBlock | Optional | - | 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:
| Properties | Type | Required | Default | Description |
|---|---|---|---|---|
recordTs | BOOL | Optional | false | Whether to record the timestamp of the edits. |
recordUserId | BOOL | Optional | false | Whether 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, thevalueof 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
majorRevisionproperty in theAgoraRtmMetadatadata type. - Enable version number verification for a single metadata item by setting the
revisionproperty in theAgoraRtmMetadataItemclass.
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;| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
userId | NSString | Required | userId of the current user | User ID. |
data | AgoraRtmMetadata | Required | - | Metadata item. See AgoraRtmMetadata. |
options | AgoraRtmMetadataOptions | Optional | - | Options for setting the channel metadata. |
completionBlock | AgoraRtmOperationBlock | Optional | - | 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:
| Properties | Type | Required | Default | Description |
|---|---|---|---|---|
recordTs | BOOL | Optional | false | Whether to record the timestamp of the edits. |
recordUserId | BOOL | Optional | false | Whether 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;| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
userId | NSString | Required | userId of the current user | User ID. |
completionBlock | AgoraRtmGetMetadataBlock | Optional | - | 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:
| Properties | Type | Description |
|---|---|---|
data | AgoraRtmMetadata | Metadata 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;| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
userId | NSString | Required | userId of the current user | User ID. |
data | AgoraRtmMetadata | Required | - | Metadata item. See AgoraRtmMetadata. |
options | AgoraRtmMetadataOptions | Optional | - | Options for setting the channel metadata. |
completionBlock | AgoraRtmOperationBlock | Optional | - | 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:
| Properties | Type | Required | Default | Description |
|---|---|---|---|---|
recordTs | BOOL | Optional | false | Whether to record the timestamp of the edits. |
recordUserId | BOOL | Optional | false | Whether 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;| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
userId | NSString | Required | userId of the current user | User ID. |
data | AgoraRtmMetadata | Required | - | Metadata item. See AgoraRtmMetadata. |
options | AgoraRtmMetadataOptions | Optional | - | Options for setting the channel metadata. |
completionBlock | AgoraRtmOperationBlock | Optional | - | 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:
| Properties | Type | Required | Default | Description |
|---|---|---|---|---|
recordTs | BOOL | Optional | false | Whether to record the timestamp of the edits. |
recordUserId | BOOL | Optional | false | Whether 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;| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
userId | NSString | Required | userId of the current user | User ID. |
completionBlock | AgoraRtmOperationBlock | Optional | - | 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;| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
userId | NSString | Required | userId of the current user | User ID. |
completionBlock | AgoraRtmOperationBlock | Optional | - | 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:
| Properties | Type | Required | Default | Description |
|---|---|---|---|---|
majorRevision | long long | Optional | -1 | The 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. |
items | NSArray<AgoraRtmMetadataItem *> | Optional | nil | Metadata items. |
The AgoraRtmMetadataItem data type contains the following properties:
| Properties | Type | Required | Default | Description |
|---|---|---|---|---|
key | NSString | Required | - | Key. |
value | NSString | Required | - | Value. |
authorUserId | NSString | Required | - | The user ID of the editor. This value is read-only and does not support writing. |
revision | long long | Optional | -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. |
updateTs | long long | Optional | 0 | Update 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;| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | NSString | Required | - | Channel name. |
channelType | AgoraRtmChannelType | Required | - | Channel types. See AgoraRtmChannelType. |
lockName | NSString | Required | - | Lock name. |
ttl | int | Optional | 10 | The 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. |
completionBlock | AgoraRtmOperationBlock | Optional | - | 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;| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | NSString | Required | - | Channel name. |
channelType | AgoraRtmChannelType | Required | - | Channel types. See AgoraRtmChannelType. |
lockName | NSString | Required | - | Lock name. |
retry | BOOL | Required | - | If the lock acquisition fails, whether to retry until the acquisition succeeds or the user leaves the channel. |
completionBlock | AgoraRtmOperationBlock | Optional | - | 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;| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | NSString | Required | - | Channel name. |
channelType | AgoraRtmChannelType | Required | - | Channel types. See AgoraRtmChannelType. |
lockName | NSString | Required | - | Lock name. |
completionBlock | AgoraRtmOperationBlock | Optional | - | 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;| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | NSString | Required | - | Channel name. |
channelType | AgoraRtmChannelType | Required | - | Channel types. See AgoraRtmChannelType. |
lockName | NSString | Required | - | Lock name. |
userId | NSString | Required | - | The ID of the user who has a lock. |
completionBlock | AgoraRtmOperationBlock | Optional | - | 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;| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | NSString | Required | - | Channel name. |
channelType | AgoraRtmChannelType | Required | - | Channel types. See AgoraRtmChannelType. |
completionBlock | AgoraRtmGetLocksBlock | Optional | - | 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:
| Properties | Type | Description |
|---|---|---|
lockDetailList | NSArray<AgoraRtmLockDetail *> | Lock details array. |
The AgoraRtmLockDetail data type contains the following properties:
| Properties | Type | Description |
|---|---|---|
lockName | NSString | Lock name. |
owner | NSString | The ID of the user who has a lock. |
ttl | int | The 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;| Parameters | Type | Required | Default | Description |
|---|---|---|---|---|
channelName | NSString | Required | - | Channel name. |
channelType | AgoraRtmChannelType | Required | - | Channel types. See AgoraRtmChannelType. |
lockName | NSString | Required | - | Lock name. |
completionBlock | AgoraRtmOperationBlock | Optional | - | 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.
| Value | Description |
|---|---|
AgoraRtmAreaCodeCN | 0x00000001: Mainland China. |
AgoraRtmAreaCodeNA | 0x00000002: North America. |
AgoraRtmAreaCodeEU | 0x00000004: Europe. |
AgoraRtmAreaCodeAS | 0x00000008: Asia, excluding Mainland China. |
AgoraRtmAreaCodeJP | 0x00000010: Japan. |
AgoraRtmAreaCodeIN | 0x00000020: India. |
AgoraRtmAreaCodeGLOB | 0xFFFFFFFF: Global. |
AgoraRtmChannelType
Channel types.
| Value | Description |
|---|---|
AgoraRtmChannelTypeMessage | 1: Message channel. |
AgoraRtmChannelTypeStream | 2: Stream channel. |
AgoraRtmChannelTypeUser | 3: User Channel. |
AgoraRtmClientConnectionChangeReason
Reasons causing the change of the connection state.
| Value | Description |
|---|---|
AgoraRtmClientConnectionChangedConnecting | 0: The SDK is connecting with the server. |
AgoraRtmClientConnectionChangedJoinSuccess | 1: The SDK has joined the channel successfully. |
AgoraRtmClientConnectionChangedInterrupted | 2: The connection between the SDK and the server is interrupted. |
AgoraRtmClientConnectionChangedBannedByServer | 3: The connection between the SDK and the server is banned by the server. |
AgoraRtmClientConnectionChangedJoinFailed | 4: 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. |
AgoraRtmClientConnectionChangedLeaveChannel | 5: The SDK has left the channel. |
AgoraRtmClientConnectionChangedInvalidAppId | 6: The connection failed because the App ID is not valid. |
AgoraRtmClientConnectionChangedInvalidChannelName | 7: The connection failed because the channel name is not valid. |
AgoraRtmClientConnectionChangedInvalidToken | 8: The connection failed because the token is not valid. |
AgoraRtmClientConnectionChangedTokenExpired | 9: The connection failed because the token is expired. |
AgoraRtmClientConnectionChangedRejectedByServer | 10: The connection is rejected by server. |
AgoraRtmClientConnectionChangedSettingProxyServer | 11: The connection state changed to reconnecting because the SDK has set a proxy server. |
AgoraRtmClientConnectionChangedRenewToken | 12: The connection state changed because the token is renewed. |
AgoraRtmClientConnectionChangedClientIpAddressChanged | 13: The IP address of the client has changed, possibly because the network type, IP address, or port has been changed. |
AgoraRtmClientConnectionChangedKeepAliveTimeout | 14: Timeout for the keep-alive of the connection between the SDK and the server. The connection state changes to reconnecting. |
AgoraRtmClientConnectionChangedRejoinSuccess | 15: The user has rejoined the channel successfully. |
AgoraRtmClientConnectionChangedChangedLost | 16: The connection between the SDK and the server is lost. |
AgoraRtmClientConnectionChangedEchoTest | 17: The connection state changes due to the echo test. |
AgoraRtmClientConnectionChangedClientIpAddressChangedByUser | 18: The local IP address was changed by the user. The connection state changes to reconnecting. |
AgoraRtmClientConnectionChangedSameUidLogin | 19: The user joined the same channel from different devices with the same UID. |
AgoraRtmClientConnectionChangedTooManyBroadcasters | 20: The number of hosts in the channel has reached the upper limit. |
AgoraRtmClientConnectionChangedStreamChannelNotAvailable | 22: The stream channel does not exist. |
AgoraRtmClientConnectionChangedLoginSuccess | 10001: The SDK logs in to the Signaling system. |
AgoraRtmClientConnectionChangedLogout | 10002: The SDK logs out from the Signaling system. |
AgoraRtmClientConnectionChangedPresenceNotReady | 10003: 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.
| Value | Description |
|---|---|
AgoraRtmClientConnectionStateDisconnected | 1: The SDK has disconnected with the server. |
AgoraRtmClientConnectionStateConnecting | 2: The SDK is connecting with the server. |
AgoraRtmClientConnectionStateConnected | 3: The SDK has connected with the server. |
AgoraRtmClientConnectionStateReconnecting | 4: The connection is lost. The SDK is reconnecting with the server. |
AgoraRtmClientConnectionStateFailed | 5: The SDK failed to connect with the server. |
AgoraRtmEncryptionMode
Encryption mode.
| Value | Description |
|---|---|
AgoraRtmEncryptionNone | 0: No encryption. |
AgoraRtmEncryptionAES128GCM | 1: AES-128-GCM mode. |
AgoraRtmEncryptionAES256GCM | 2: 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.
| Value | Description |
|---|---|
AgoraRtmJoinChannelFeatureNone | 0: No event notifications. |
AgoraRtmJoinChannelFeaturePresence | 1: Sets the presence event notification. |
AgoraRtmJoinChannelFeatureMetadata | 1 << 1: Sets the storage event notification. |
AgoraRtmJoinChannelFeatureLock | 1 << 2: Sets the lock event notification. |
AgoraRtmJoinChannelFeatureBeQuiet | 1 << 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.
| Value | Description |
|---|---|
AgoraRtmLockEventTypeSnapshot | 1: The snapshot of the lock when the user joined the channel. |
AgoraRtmLockEventTypeLockSet | 2: The lock is set. |
AgoraRtmLockEventTypeLockRemoved | 3: The lock is removed. |
AgoraRtmLockEventTypeLockAcquired | 4: The lock is acquired. |
AgoraRtmLockEventTypeLockReleased | 5: The lock is released. |
AgoraRtmLockEventTypeLockExpired | 6: The lock expired. |
AgoraRtmLogLevel
Log output levels.
| Value | Description |
|---|---|
AgoraRtmLogLevelNone | 0x0000: No log. |
AgoraRtmLogLevelInfo | 0x0001: Output the log at the FATAL, ERROR, WARN, or INFO level. We recommend you set to this value. |
AgoraRtmLogLevelWarn | 0x0002: Output the log at the FATAL, ERROR, WARN level. |
AgoraRtmLogLevelError | 0x0004: Output the log at the FATAL, ERROR level. |
AgoraRtmLogLevelFatal | 0x0008: Output the log at the FATAL level. |
AgoraRtmMessagePriority
Message priority.
| Value | Description |
|---|---|
AgoraRtmMessagePriorityHighest | 0: Highest. |
AgoraRtmMessagePriorityHigh | 1: High. |
AgoraRtmMessagePriorityNormal | 4: Normal. |
AgoraRtmMessagePriorityLow | 8: Low. |
AgoraRtmMessageQos
QoS guarantee when sending topic messages.
| Value | Description |
|---|---|
AgoraRtmMessageQosUnordered | 0: Message data is not guaranteed to arrive in order. |
AgoraRtmMessageQosOrdered | 1: Message data arrives in order. |
AgoraRtmPresenceEventType
Presence event type.
| Value | Description |
|---|---|
AgoraRtmPresenceEventTypeSnapshot | 1: The snapshot of the presence when the user joined the channel. |
AgoraRtmPresenceEventTypeInterval | 2: When users in the channel reach the setting value, the event notifications are sent at intervals rather than in real time. |
AgoraRtmPresenceEventTypeRemoteJoinChannel | 3: A remote user joined the channel. |
AgoraRtmPresenceEventTypeRemoteLeaveChannel | 4: A remote user left the channel. |
AgoraRtmPresenceEventTypeRemoteConnectionTimeout | 5: A remote user's connection timed out. |
AgoraRtmPresenceEventTypeRemoteStateChanged | 6: A remote user's temporary state changed. |
AgoraRtmPresenceEventTypeErrorOutOfService | 7: The user did not enable presence when joining the channel. |
AgoraRtmLinkOperation
Operation type.
| Value | Description |
|---|---|
AgoraRtmLinkOperationLogin | 0: The user logins to the Signaling system. |
AgoraRtmLinkOperationLogout | 1: The user logouts of the Signaling system. |
AgoraRtmLinkOperationJoin | 2: The user joins in a stream channel. |
AgoraRtmLinkOperationLeave | 3: The user leaves a stream channel. |
AgoraRtmLinkOperationServerReject | 4: The Signaling server reject the connection. |
AgoraRtmLinkOperationAutoReconnect | 5: The SDK is automatically reconnecting to the Signaling server. |
AgoraRtmLinkOperationReconnected | 6: The SDK is reconnected to the Signaling server. |
AgoraRtmLinkOperationHeartbeatTimeout | 7: The Signaling server does not receive the heartbeat packet within the specified timeout period. |
AgoraRtmLinkOperationServerTimeout | 8: The Signaling server has timed out. |
AgoraRtmLinkOperationNetworkChange | 9: The network status changes. |
AgoraRtmLinkState
Link state type.
| Value | Description |
|---|---|
AgoraRtmLinkStateIdle | 0: The init state. |
AgoraRtmLinkStateConnecting | 1: Connecting. |
AgoraRtmLinkStateConnected | 2: Connected. |
AgoraRtmLinkStateDisconnected | 3: Disconnected. |
AgoraRtmLinkStateSuspended | 4: Suspended. |
AgoraRtmLinkStateFailed | 5: Failed. |
AgoraRtmLinkStateChangeReason
Link state change reason.
| Value | Description |
|---|---|
AgoraRtmLinkStateChangeReasonUnknown | 0: Unknown reason. |
AgoraRtmLinkStateChangeReasonLogin | 1: Logging in. |
AgoraRtmLinkStateChangeReasonLoginSuccess | 2: Login successful. |
AgoraRtmLinkStateChangeReasonLoginTimeout | 3: Login timeout. |
AgoraRtmLinkStateChangeReasonLoginNotAuthorized | 4: Login not authorized. |
AgoraRtmLinkStateChangeReasonLoginRejected | 5: Login rejected. |
AgoraRtmLinkStateChangeReasonRelogin | 6: Re-login. |
AgoraRtmLinkStateChangeReasonLogout | 7: Logout. |
AgoraRtmLinkStateChangeReasonAutoReconnect | 8: Auto-reconnect. |
AgoraRtmLinkStateChangeReasonReconnectTimeout | 9: Reconnect timeout. |
AgoraRtmLinkStateChangeReasonReconnectSuccess | 10: Reconnect successful. |
AgoraRtmLinkStateChangeReasonJoin | 11: Joining a channel. |
AgoraRtmLinkStateChangeReasonJoinSuccess | 12: Join channel successful. |
AgoraRtmLinkStateChangeReasonJoinFailed | 13: Join channel failed. |
AgoraRtmLinkStateChangeReasonRejoin | 14: Re-join a channel. |
AgoraRtmLinkStateChangeReasonLeave | 15: Leave a channel. |
AgoraRtmLinkStateChangeReasonInvalidToken | 16: Invalid token. |
AgoraRtmLinkStateChangeReasonTokenExpired | 17: Token expired. |
AgoraRtmLinkStateChangeReasonInconsistentAppId | 18: Inconsistent app ID. |
AgoraRtmLinkStateChangeReasonInvalidChannelName | 19: Invalid channel name. |
AgoraRtmLinkStateChangeReasonInvalidUserId | 20: Invalid user ID. |
AgoraRtmLinkStateChangeReasonNotInitialized | 21: SDK not initialized. |
AgoraRtmLinkStateChangeReasonRtmServiceNotConnected | 22: RTM service not connected. |
AgoraRtmLinkStateChangeReasonChannelInstanceExceedLimitation | 23: Channel instance exceeds the limit. |
AgoraRtmLinkStateChangeReasonOperationRateExceedLimitation | 24: Operation frequency exceeds the limit. |
AgoraRtmLinkStateChangeReasonChannelInErrorState | 25: Channel in error state. |
AgoraRtmLinkStateChangeReasonPresenceNotConnected | 26: Presence service not connected. |
AgoraRtmLinkStateChangeReasonSameUidLogin | 27: Login with the same user ID. |
AgoraRtmLinkStateChangeReasonKickedOutByServer | 28: Kicked out by the server. |
AgoraRtmLinkStateChangeReasonKeepAliveTimeout | 29: Keepalive timeout. |
AgoraRtmLinkStateChangeReasonConnectionError | 30: Connection error. |
AgoraRtmLinkStateChangeReasonPresenceNotReady | 31: Presence service not ready. |
AgoraRtmLinkStateChangeReasonNetworkChange | 32: Network changed. |
AgoraRtmLinkStateChangeReasonServiceNotSupported | 33: Service not supported. |
AgoraRtmLinkStateChangeReasonStreamChannelNotAvailable | 34: Stream Channel not available. |
AgoraRtmLinkStateChangeReasonStorageNotAvailable | 35: Storage service not available. |
AgoraRtmLinkStateChangeReasonLockNotAvailable | 36: Lock service not available. |
AgoraRtmLinkStateChangeReasonLoginTooFrequent | 37: The login operation is too frequent. |
AgoraRtmProtocolType
Protocol type.
| Value | Description |
|---|---|
AgoraRtmProtocolTypeTcpUdp | 0: Both TCP and UDP protocols. |
AgoraRtmProtocolTypeTcpOnly | 1: Only TCP protocol. |
AgoraRtmServiceType
Service type
| Value | Description |
|---|---|
AgoraRtmServiceTypeMessage | The foundational services comprise the message channel, user channel, presence, storage, and lock services. |
AgoraRtmServiceTypeStream | The stream channel service. |
Information
To fully utilize all services offered by Signaling, use bitwise operations to simultaneously configure two service types.
AgoraRtmProxyType
Proxy type.
| Value | Description |
|---|---|
AgoraRtmProxyTypeNone | 0: Do not enable the proxy. |
AgoraRtmProxyTypeHttp | 1: Enable the proxy for the HTTP protocol. |
AgoraRtmProxyTypeCloudTcp | 2: Enable cloud proxy for the TCP protocol. |
AgoraRtmStorageEventType
Storage event type.
| Value | Description |
|---|---|
AgoraRtmStorageEventTypeSnapshot | 1: 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. |
AgoraRtmStorageEventTypeSet | 2: Occurs when calling setChannelMetadata or setUserMetadata. Caution: This event only occurs in incremental data update mode. |
AgoraRtmStorageEventTypeUpdate | 3: Occurs when calling methods to set, update, or delete the channel metadata or user metadata. |
AgoraRtmStorageEventTypeRemove | 4: Occurs when calling removeChannelMetadata or removeUserMetadata. Caution: This event only occurs in incremental data update mode. |
AgoraRtmStorageType
Storage type.
| Value | Description |
|---|---|
AgoraRtmStorageTypeUser | 1: User metadata event. |
AgoraRtmStorageTypeChannel | 2: 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.
| Value | Description |
|---|---|
AgoraRtmSubscribeChannelFeatureNone | 0: No event notifications |
AgoraRtmSubscribeChannelFeaturePresence | 1: Sets the presence event notification. |
AgoraRtmSubscribeChannelFeatureMetadata | 1 << 1: Sets the storage event notification. |
AgoraRtmSubscribeChannelFeatureMessage | 1 << 2: Sets the message event notification. |
AgoraRtmSubscribeChannelFeatureLock | 1 << 3: Sets the lock event notification. |
AgoraRtmSubscribeChannelFeatureBeQuiet | 1 << 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.
| Value | Description |
|---|---|
AgoraRtmTopicEventTypeSnapshot | 1: The snapshot of the topic when the user joined the channel. |
AgoraRtmTopicEventTypeRemoteJoinTopic | 2: A remote user joined the channel. |
AgoraRtmTopicEventTypeRemoteLeaveTopic | 3: A remote user left the channel. |
Troubleshooting
Refer to the following information for troubleshooting API calls.
ErrorInfo
| Properties | Type | Description |
|---|---|---|
errorCode | AgoraRtmErrorCode | Error code for this operation. |
reason | NSString | Error reason for this operation. |
operation | NSString | Operation 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 code | Error description | Cause and solution |
|---|---|---|
0 | AgoraRtmErrorOk | Correct call |
-10001 | AgoraRtmErrorNotInitialized | The SDK is not initialized. Please initialize the RtmClient instance by calling the initWithConfig method before performing other operations. |
-10002 | AgoraRtmErrorNotLogin | The user called the API without logging in to Signaling, disconnected due to timeout, or actively logged out. Please log in to Signaling first. |
-10003 | AgoraRtmErrorInvalidAppId | Invalid App ID: - Check that the App ID is correct. - Ensure that Signaling has been activated for the App ID. |
-10005 | AgoraRtmErrorInvalidToken | Invalid Token: - The token is invalid, check whether the Token Provider generates a valid Signaling Token. |
-10006 | AgoraRtmErrorInvalidUserId | Invalid User ID: - Check if user ID is empty. - Check if the user ID contains illegal characters. |
-10007 | AgoraRtmErrorInitServiceFailed | SDK initialization failed. Please reinitialize by calling the initWithConfig method. |
-10008 | AgoraRtmErrorInvalidChannelName | Invalid channel name: - Check if the channel name is empty. - Check if the channel name contains illegal characters. |
-10009 | AgoraRtmErrorTokenExpired | Token expired. Call renewToken to reacquire the Token. |
-10010 | AgoraRtmErrorLoginNoServerResources | Server resources are limited. It is recommended to log in again. |
-10011 | AgoraRtmErrorLoginTimeout | Login timeout. Check whether the current network is stable and switch to a stable network environment. |
-10012 | AgoraRtmErrorLoginRejected | SDK login rejected by the server: - Check tha Signaling is activated on your App ID. - Check if the token or userId is banned. |
-10013 | AgoraRtmErrorLoginAborted | SDK 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. |
-10014 | AgoraRtmErrorInvalidParameter | Invalid parameter. Please check if the parameters you provided are correct. |
-10015 | AgoraRtmErrorLoginNotAuthorized | No RTM service permissions. Check that the console opens Signaling services. |
-10016 | AgoraRtmErrorLoginInconsistentAppId | Inconsistent App ID. Please check whether the App ID used for initialization, login, and joining a channel are consistent. |
-10017 | AgoraRtmErrorDuplicateOperation | Duplicate operation. |
-10018 | AgoraRtmErrorInstanceAlreadyReleased | Repeat rtm instantiation or RTMStreamChannel instantiation. |
-10019 | AgoraRtmErrorInvalidChannelType | Invalid channel type. The SDK only supports the following channel types. Please use the correct value: - AgoraRtmChannelTypeMessage: Message Channel - AgoraRtmChannelTypeStream: Stream Channel - AgoraRtmChannelTypeUser: User Channel |
-10020 | AgoraRtmErrorInvalidEncryptionParameter | Message 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. |
-10021 | AgoraRtmErrorOperationRateExceedLimitation | Channel metadata or User Metadata -related API call frequency is exceeding the limit. Please control the call frequency within 10/second. |
-10022 | AgoraRtmErrorServiceNotSupport | The 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. |
-10023 | AgoraRtmErrorLoginCanceled | The 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. |
-10024 | AgoraRtmErrorInvalidPrivateConfig | The private deployment parameter settings are invalid. Please check whether the service type and server address you set in AgoraRtmPrivateConfig are valid. |
-10025 | AgoraRtmErrorNotConnected | Not 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. |
-10026 | AgoraRtmErrorRenewTokenTimeout | Token renewal timed out. |
-11001 | AgoraRtmErrorChannelNotJoined | The user has not joined the channel: - The user is not online, offline or has not joined the channel - Check for typos in userId. |
-11002 | AgoraRtmErrorChannelNotSubscribed | The user has not subscribed to the channel: - The user is not online, offline or has not joined the channel - Check for typos in userId. |
-11003 | AgoraRtmErrorChannelExceedTopicUserLimitation | The number of subscribers to this topic exceeds the limit. |
-11004 | AgoraRtmErrorChannelReused | In co-channel mode, RTM released the Stream Channel. |
-11005 | AgoraRtmErrorChannelInstanceExceedLimitation | The number of created or subscribed channels exceeds the limit. See API usage limits for details. |
-11006 | AgoraRtmErrorChannelInErrorState | Channel is not available. Please recreate the Stream Channel or resubscribe to the Message Channel. |
-11007 | AgoraRtmErrorChannelJoinFailed | Failed 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. |
-11008 | AgoraRtmErrorChannelInvalidTopicName | Invalid topic name: - Check whether the topic name contains illegal characters. - Check if the topic name is empty. |
-11009 | AgoraRtmErrorChannelInvalidMessage | Invalid message. Check whether the message type is legal, Signaling only supports string, Uint8Array type messages. |
-11010 | AgoraRtmErrorChannelMessageLengthExceedLimitation | Message 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. |
-11011 | AgoraRtmErrorChannelInvalidUserList | Invalid user list: - Check if the user list is empty. - Check if the user list contains invalid entries. |
-11012 | AgoraRtmErrorChannelNotAvailable | Invalid user list: - Check if the user list is empty - Check if the user list contains illegal items. |
-11013 | AgoraRtmErrorChannelTopicNotSubscribed | The topic is not subscribed. |
-11014 | AgoraRtmErrorChannelExceedTopicLimitation | The number of topics exceeds the limit. |
-11015 | AgoraRtmErrorChannelJoinTopicFailed | Failed to join this topic. Check whether the number of added topics exceeds the limit. |
-11016 | AgoraRtmErrorChannelTopicNotJoined | The topic has not been joined. To send a message, you need to join the Topic first. |
-11017 | AgoraRtmErrorChannelTopicNotExist | The topic does not exist. Check that the topic name is correct. |
-11018 | AgoraRtmErrorChannelInvalidTopicMeta | The meta parameters in the topic are invalid. Check if the meta parameter exceeds 256 bytes. |
-11019 | AgoraRtmErrorChannelSubscribeTimeout | Channel subscription timed out. Check for broken connections. |
-11020 | AgoraRtmErrorChannelSubscribeTooFrequent | The 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. |
-11021 | AgoraRtmErrorChannelSubscribeFailed | Channel subscription failed.11003 Check if the number of subscribed channels exceeds the limit. |
-11022 | AgoraRtmErrorChannelUnsubscribeFailed | Failed to unsubscribe from the channel. Check if the connection is disconnected. |
-11023 | AgoraRtmErrorChannelEncryptMessageFailed | Message encryption failed: - Check that the cipherKey is valid. - Check that the salt is valid. - Check if encryptionMode mode matches the cipherKey and salt. |
-11024 | AgoraRtmErrorChannelPublishMessageFailed | Message publishing failed. Check for broken connections. |
-11026 | AgoraRtmErrorChannelPublishMessageTimeout | Message publishing timed out. Check for broken connections. |
-11027 | AgoraRtmErrorChannelNotConnected | The SDK is disconnected from the Signaling server. Please log in again. |
-11028 | AgoraRtmErrorChannelLeaveFailed | Failed to leave the channel. Check for broken connections. |
-11029 | AgoraRtmErrorChannelCustomTypeLengthOverflow | Custom type length overflow. The length of the customType field must to be within 32 characters. |
-11030 | AgoraRtmErrorChannelInvalidCustomType | customType field is invalid. Check the customType field for illegal characters. |
-11031 | AgoraRtmErrorChannelUnsupportedMessageType | Message type is not supported. |
-11032 | AgoraRtmErrorChannelPresenceNotReady | Presence service is not ready. Please rejoin the Stream Channel or resubscribe to the Message Channel. |
-11033 | AgoraRtmErrorChannelReceiverOffline | When 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. |
-11034 | AgoraRtmErrorChannelJoinCanceled | The 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. |
-12001 | AgoraRtmErrorStorageOperationFailed | Storage operation failed. |
-12002 | AgoraRtmErrorStorageMetadataItemExceedLimitation | The number of Storage Metadata Items exceeds the limit. |
-12003 | AgoraRtmErrorStorageInvalidMetadataItem | Invalid Metadata Item. |
-12004 | AgoraRtmErrorStorageInvalidArgument | Invalid argument. |
-12005 | AgoraRtmErrorStorageInvalidRevision | Invalid Revision parameter. |
-12006 | AgoraRtmErrorStorageMetadataLengthOverflow | Metadata overflows. |
-12007 | AgoraRtmErrorStorageInvalidLockName | Invalid Lock name. |
-12008 | AgoraRtmErrorStorageLockNotAcquired | The Lock was not acquired. |
-12009 | AgoraRtmErrorStorageInvalidKey | Invalid Metadata key. |
-12010 | AgoraRtmErrorStorageInvalidValue | Invalid metadata value. |
-12011 | AgoraRtmErrorStorageKeyLengthOverflow | Metadata key length overflow. |
-12012 | AgoraRtmErrorStorageValueLengthOverflow | Metadata value length overflow. |
-12013 | AgoraRtmErrorStorageDuplicateKey | Duplicate Metadata Item key. |
-12014 | AgoraRtmErrorStorageOutdatedRevision | Outdated Revision parameter. |
-12015 | AgoraRtmErrorStorageNotSubscribe | This channel is not subscribed. |
-12016 | AgoraRtmErrorStorageInvalidMetadataInstance | Metadata instance does not exist. Please create a Metadata instance. |
-12017 | AgoraRtmErrorStorageSubscribeUserExceedLimitation | The number of subscribers exceeds the limit. |
-12018 | AgoraRtmErrorStorageOperationTimeout | Storage operation timed out. |
-12019 | AgoraRtmErrorStorageNotAvailable | The Storage service is not available. |
-13001 | AgoraRtmErrorPresenceNotConnected | The user is not connected to the system. |
-13002 | AgoraRtmErrorPresenceNotWritable | Presence service is unavailable. |
-13003 | AgoraRtmErrorPresenceInvalidArgument | Invalid argument. |
-13004 | AgoraRtmErrorPresenceCacheTooManyStates | The temporary user state cached before joining the channel exceeds the limit. See API usage limits for details. |
-13005 | AgoraRtmErrorPresenceStateCountOverflow | The number of temporary user state key/value pairs exceeds the limit. See API usage limits for details. |
-13006 | AgoraRtmErrorPresenceInvalidStateKey | Invalid state key. |
-13007 | AgoraRtmErrorPresenceInvalidStateValue | Invalid state value. |
-13008 | AgoraRtmErrorPresenceStateKeySizeOverflow | Presence key length overflow. |
-13009 | AgoraRtmErrorPresenceStateValueSizeOverflow | Presence value overflow |
-13010 | AgoraRtmErrorPresenceStateDuplicateKey | Repeated state key. |
-13011 | AgoraRtmErrorPresenceUserNotExist | The user does not exist. |
-13012 | AgoraRtmErrorPresenceOperationTimeout | Presence operation timed out. |
-13013 | AgoraRtmErrorPresenceOperationFailed | Presence operation failed. |
-14001 | AgoraRtmErrorLockOperationFailed | Lock operation failed. |
-14002 | AgoraRtmErrorLockOperationTimeout | Lock operation timed out. |
-14003 | AgoraRtmErrorLockOperationPerforming | Lock operation in progress. |
-14004 | AgoraRtmErrorLockAlreadyExist | Lock already exists. |
-14005 | AgoraRtmErrorLockInvalidName | Invalid Lock name. |
-14006 | AgoraRtmErrorLockNotAcquired | The Lock was not acquired. |
-14007 | AgoraRtmErrorLockAcquireFailed | Failed to acquire the Lock. |
-14008 | AgoraRtmErrorLockNotExist | The Lock does not exist. |
-14009 | AgoraRtmErrorLockNotAvailable | Lock service is not available. |
