# macOS (/en/api-reference/api-ref/signaling/macos)

> For AI agents: see the complete documentation index at [llms.txt](/llms.txt).

<CalloutContainer type="info">
  <CalloutDescription>
    This is the Objective-C API reference. For Swift, see the [iOS SDK API reference](ios).
  </CalloutDescription>
</CalloutContainer>

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

* [Setup](#setup)
* [User authentication](#user-authentication)
* [Channels](#channels)
* [Topics](#topics)
* [Messages](#messages)
* [Presence](#presence)
* [Storage](#storage)
* [Lock](#lock)
* [Enumerated types](#enumerated-types)
* [Troubleshooting](#troubleshooting)

## Setup [#setup]

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

### AgoraRtmClientConfig [#agorartmclientconfig]

#### Description [#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 [#method]

You can create `AgoraRtmClientConfig` instances as follows:

```objc
__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`](#enumvareacod-e).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
|    `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`](#enumvprotocoltyp-e).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
|  `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: <br />- 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`. <br />- 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:<br />- `true`: Use string-type user IDs. <br />- `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: <br />- `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. <br />- `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 [#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].<br />- If the value you enter is less than 128, the SDK sets the value to 128.<br />- 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`](#enumvlogleve-l).                                                                                                                                                |

##### AgoraRtmProxyConfig [#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.

<CalloutContainer type="warning">
  <CalloutTitle>
    Caution
  </CalloutTitle>

  <CalloutDescription>
    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.
  </CalloutDescription>
</CalloutContainer>

`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`](#enumvproxytyp-e). |
|   `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 [#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.

<CalloutContainer type="warning">
  <CalloutTitle>
    Caution
  </CalloutTitle>

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

`AgoraRtmEncryptionConfig` contains the following properties:

|      Properties     |           Type           | Required |          Default         | Description                                                                                                           |
| :-----------------: | :----------------------: | :------: | :----------------------: | --------------------------------------------------------------------------------------------------------------------- |
|   `encryptionMode`  | `AgoraRtmEncryptionMode` | Optional | `AgoraRtmEncryptionNone` | Encryption mode. See [`AgoraRtmEncryptionMode`](#enumvencryptionmod-e).                                               |
|   `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 [#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&lt;RtmServiceType&gt;` | Optional |    -    | Service type. See [`AgoraRtmServiceType`](#enumvrtmservicetyp-e).                 |
| `accessPointHosts` |   `NSArray&lt;NSString *&gt;`   | Optional |    -    | An array of server addresses, where you can fill in domain names or IP addresses. |

#### Basic usage [#basic-usage]

```objc
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 [#create-an-instance]

#### Description [#description-1]

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

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    <br />- You need to create and initialize a client instance before calling other Signaling APIs. <br />- 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.
  </CalloutDescription>
</CalloutContainer>

#### Method [#method-1]

You can create and initialize an instance as follows:

```objc
- (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 &lt;AgoraRtmClientDelegate&gt;` | Optional | -       | Signaling event notification listener settings. See [Event listeners](#event-listeners).     |
|   `error`  |               NSError               | Required | -       | (Output) Error description.                                                                  |

#### Basic usage [#basic-usage-1]

```objc
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 [#return-value]

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

### Event Listeners [#event-listeners]

#### DescriptionAgoraRtmClientDelegate [#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`](#configmessageeven-t) .                            |
|  `didReceivePresenceEvent` | Receive presence event notifications in subscribed message channels and joined stream channels. See [`AgoraRtmPresenceEvent`](#configpresenceeven-t)                                                                              |
|   `didReceiveTopicEvent`   | Receive all topic event notifications in joined stream channels. See [`AgoraRtmTopicEvent`](#configtopiceven-t)                                                                                                                   |
|  `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`](#configstorageeven-t)      |
|    `didReceiveLockEvent`   | Receive lock event notifications in subscribed message channels and joined stream channels. See [`AgoraRtmLockEvent`](#configlockeven-t)                                                                                          |
| `connectionChangedToState` | (Deprecated) Receive event notifications when client connection status changes. For details, see [`AgoraRtmClientConnectionState`](#enumvconnectionstat-e) and [`AgoraRtmClientConnectionChangeReason`](#enumvconnectionreaso-n). |
| `didReceiveLinkStateEvent` | Receive event notifications when client connection status changes. See [`AgoraRtmLinkStateEvent`](#configlinkstateeven-t).                                                                                                        |
| `tokenPrivilegeWillExpire` | Receive event notifications when the client tokens are about to expire.                                                                                                                                                           |

#### Add event listeners [#add-event-listeners]

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

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

##### Adding During Initialization [#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:

```objc
@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 [#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.

```objc
@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.

```objc
[rtm removeDelegate:handlerEx];
```

##### AgoraRtmMessageEvent [#agorartmmessageevent]

Message event.

`AgoraRtmMessageEvent` contains the following properties:

|   Properties   |          Type         | Description                                                     |
| :------------: | :-------------------: | --------------------------------------------------------------- |
|  `channelType` | `AgoraRtmChannelType` | Channel types. See [`AgoraRtmChannelType`](#enumvchanneltyp-e). |
|  `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 [#agorartmpresenceevent]

User presence event.

`AgoraRtmPresenceEvent` contains the following properties:

|   Properties  |                 Type                 | Description                                                                                                                                                                                   |
| :-----------: | :----------------------------------: | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|     `type`    |      `AgoraRtmPresenceEventType`     | Presence event type. See [`AgoraRtmPresenceEventType`](#enumvpresencetyp-e).                                                                                                                  |
| `channelType` |         `AgoraRtmChannelType`        | Channel types. See [`AgoraRtmChannelType`](#enumvchanneltyp-e).                                                                                                                               |
| `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&lt;AgoraRtmUserState *&gt;` | When the user first joins the channel, the server pushes the snapshot data of all users in the current channel and their statuses to the user.                                                |
|  `timestamp`  |          unsigned long long          | The timestamp when the event occurs.                                                                                                                                                          |

The `AgoraRtmPresenceIntervalInfo` data type contains the following properties:

| Properties        |             Type             | Description                                                                                                |
| :---------------- | :--------------------------: | :--------------------------------------------------------------------------------------------------------- |
| `joinUserList`    |  `NSArray&lt;NSString *&gt;` | List of users who joined the channel in the previous cycle.                                                |
| `leaveUserList`   |  `NSArray&lt;NSString *&gt;` | List of users who left the channel in the previous cycle.                                                  |
| `timeoutUserList` |  `NSArray&lt;NSString *&gt;` | List of users who timed out joining the channel in the previous cycle.                                     |
| `userStateList`   | `ArrayList&lt;UserState&gt;` | List of users whose status has changed in the previous cycle. Contains user ID and status key-value pairs. |

The `AgoraRtmUserState` data type contains the following properties:

| 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 [#agorartmtopicevent]

Topic event.

`AgoraRtmTopicEvent` contains the following properties:

|   Properties  |                 Type                 | Description                                                         |
| :-----------: | :----------------------------------: | ------------------------------------------------------------------- |
|     `type`    |       `AgoraRtmTopicEventType`       | Topic event type. See [`AgoraRtmTopicEventType`](#enumvtopictyp-e). |
| `channelName` |               NSString               | Channel name.                                                       |
|  `publisher`  |               NSString               | User ID.                                                            |
|  `topicInfos` | `NSArray&lt;AgoraRtmTopicInfo *&gt;` | 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&lt;AgoraRtmPublisherInfo *&gt;` | 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 [#agorartmstorageevent]

Storage event.

`AgoraRtmStorageEvent` contains the following properties:

|   Properties  |            Type            | Description                                                                    |
| :-----------: | :------------------------: | ------------------------------------------------------------------------------ |
| `channelType` |    `AgoraRtmChannelType`   | Channel types. See [`AgoraRtmChannelType`](#enumvchanneltyp-e).                |
| `storageType` |    `AgoraRtmStorageType`   | Storage type. See [`AgoraRtmStorageType`](#enumvstoragetyp-e).                 |
|  `eventType`  | `AgoraRtmStorageEventType` | Storage event type. See [`AgoraRtmStorageEventType`](#enumvstorageeventtyp-e). |
|    `target`   |          NSString          | User ID or channel name.                                                       |
|     `data`    |     `AgoraRtmMetadata`     | Metadata item. See [`AgoraRtmMetadata`](#storagemetadat-a).                    |
|  `timestamp`  |     unsigned long long     | The timestamp when the event occurs.                                           |

##### AgoraRtmLockEvent [#agorartmlockevent]

Lock event.

`AgoraRtmLockEvent` contains the following properties:

|    Properties    |              Type             | Description                                                      |
| :--------------: | :---------------------------: | ---------------------------------------------------------------- |
|   `channelType`  |     `AgoraRtmChannelType`     | Channel types. See [`AgoraRtmChannelType`](#enumvchanneltyp-e).  |
|    `eventType`   |    `AgoraRtmLockEventType`    | Lock event type. See [`AgoraRtmLockEventType`](#enumvlocktyp-e). |
|   `channelName`  |            NSString           | Channel name.                                                    |
| `lockDetailList` | `ArrayList&lt;LockDetail&gt;` | 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 [#agorartmlinkstateevent]

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

|      Parameters      |               Type              | Description                                                                                                                                                                                                         |
| :------------------: | :-----------------------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|    `currentState`    |       `AgoraRtmLinkState`       | The current link state. See [`AgoraRtmLinkState`](#enumvlinkstat-e).                                                                                                                                                |
|    `previousState`   |       `AgoraRtmLinkState`       | The previous link state. See [`AgoraRtmLinkState`](#enumvlinkstat-e).                                                                                                                                               |
|     `serviceType`    |      `AgoraRtmServiceType`      | The network connection type. See [`AgoraRtmServiceType`](#enumvrtmservicetyp-e).                                                                                                                                    |
|      `operation`     |     `AgoraRtmLinkOperation`     | The operation that triggered the current state transition. See [`AgoraRtmLinkOperation`](#enumvlinkoperatio-n).                                                                                                     |
|     `reasonCode`     | `AgoraRtmLinkStateChangeReason` | The reason for this state transition. See [`AgoraRtmLinkStateChangeReason`](#enumvlinkstatereaso-n).                                                                                                                |
|       `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&lt;NSString *&gt;`   | The channels affected by the current state transition.                                                                                                                                                              |
| `unrestoredChannels` |   `NSArray&lt;NSString *&gt;`   | The information about the channels to which subscription or joining has not been restored, including the channel name, channel type, and temporary state data in the channel. Typically, this information is empty. |
|      `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 [#agorartmclientkit]

Signaling client instance

### loginByToken [#loginbytoken]

#### Description [#description-2]

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.

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

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

#### Method [#method-2]

You can log in to the Signaling system as follows:

```objc
- (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.<br />- If you have enabled token authentication for your project, use either the [Signaling temporary token](https://agora-token-generator-demo.vercel.app/) or obtain a Signaling token generated by your [token server](/en/realtime-media/rtm/build/connect-and-authenticate/authentication-workflow).<br />- 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:<br />- Success: Returns the `AgoraRtmCommonResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- Failure: Returns `nil` in the `response` parameter, and error information in the `errorInfo` parameter.                                                                                                                                                                                                                           |

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

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

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

| 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).

#### Basic usage [#basic-usage-2]

```objc
[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 [#logout]

#### Description [#description-3]

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 [#method-3]

You can log out as follows:

```objc
- (void) logout: (AgoraRtmOperationBlock _Nullable)completionBlock;
```

|     Parameters    |           Type           | Required | Default | Description                                                                                                                                                                                                                                                                  |
| :---------------: | :----------------------: | :------: | :-----: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `completionBlock` | `AgoraRtmOperationBlock` | Optional |    -    | Callback of invocation result:<br />- Success: Returns the `AgoraRtmCommonResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- Failure: Returns `nil` in the `response` parameter, and error information in the `errorInfo` parameter. |

#### Basic usage [#basic-usage-3]

```objc
[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 [#releaselock]

#### Description [#description-4]

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 [#method-4]

You can destroy the `AgoraRtmClientKit` instance as follows:

```objc
- (AgoraRtmErrorCode) destroy;
```

#### Basic usage [#basic-usage-4]

```objc
[rtm destroy];
```

#### Return Value [#return-value-1]

The `releaseLock` method returns an `AgoraRtmErrorCode` data structure. See [Error code](#error-codes-table).

## User authentication [#user-authentication]

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

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

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

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

For more information on generating and using tokens, see [Secure authentication with tokens](/en/realtime-media/rtm/build/connect-and-authenticate/authentication-workflow).

### AgoraRtmClientKit.renewToken [#agorartmclientkitrenewtoken]

#### Description [#description-5]

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](#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 [#method-5]

You can call the `AgoraRtmClientKit.renewToken` method as follows:

```objc
- (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:<br />- Success: Returns the `AgoraRtmCommonResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- Failure: Returns `nil` in the `response` parameter, and error information in the `errorInfo` parameter. |

#### Basic usage [#basic-usage-5]

```objc
[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 [#agorartmstreamchannelrenewtoken]

#### Description [#description-6]

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](#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 [#method-6]

You can call the `AgoraRtmStreamChannel.renewToken` method as follows:

```objc
- (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:<br />- Success: Returns the `AgoraRtmCommonResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- Failure: Returns `nil` in the `response` parameter, and error information in the `errorInfo` parameter. |

#### Basic usage [#basic-usage-6]

```objc
[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 [#channels]

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

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

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

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

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

AgoraRtmClientKit
Signaling client instance

### subscribeTopic [#subscribetopic]

#### Description [#description-7]

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](#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](#event-listeners).

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    This method only applies to the message channel.
  </CalloutDescription>
</CalloutContainer>

#### Method [#method-7]

You can call the `subscribeTopic` method as follows:

```objc
- (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:<br />- Success: Returns the `AgoraRtmCommonResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- 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 [#basic-usage-7]

```objc
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 [#unsubscribetopic]

#### Description [#description-8]

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](#event-listeners).

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    This method only applies to the message channel.
  </CalloutDescription>
</CalloutContainer>

#### Method [#method-8]

You can call the `unsubscribeTopic` method as follows:

```objc
- (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:<br />- Success: Returns the `AgoraRtmCommonResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- Failure: Returns `nil` in the `response` parameter, and error information in the `errorInfo` parameter. |

#### Basic usage [#basic-usage-8]

```objc
[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 [#initwithconfig]

#### Description [#description-9]

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.

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    This method only applies to the stream channel.
  </CalloutDescription>
</CalloutContainer>

#### Method [#method-9]

You can call the `initWithConfig` method as follows:

```objc
- (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 [#basic-usage-9]

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

#### Return Value [#return-value-2]

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

AgoraRtmStreamChannel
Stream channel instance

### joinTopic [#jointopic]

#### Description [#description-10]

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

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

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    This method only applies to the stream channel.
  </CalloutDescription>
</CalloutContainer>

#### Method [#method-10]

You can call the `joinTopic` method as follows:

```objc
- (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:<br />- Success: Returns the `AgoraRtmCommonResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- 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.<br />- If you have enabled token authentication for your project, generate a [temporary RTC token](/video-calling/get-started/manage-agora-account#generate-temporary-tokens) or obtain an RTC token generated by your [token server](/video-calling/token-authentication/deploy-token-server).<br />- 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 [#basic-usage-10]

```objc
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 [#leavetopic]

#### Description [#description-11]

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](#event-listeners).

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    This method only applies to the stream channel.
  </CalloutDescription>
</CalloutContainer>

#### Method [#method-11]

You can call the `leaveTopic` method as follows:

```objc
- (void)leave: (AgoraRtmOperationBlock _Nullable)completionBlock;
```

|     Parameters    |           Type           | Required | Default | Description                                                                                                                                                                                                                                                                  |
| :---------------: | :----------------------: | :------: | :-----: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `completionBlock` | `AgoraRtmOperationBlock` | Optional |    -    | Callback of invocation result:<br />- Success: Returns the `AgoraRtmCommonResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- Failure: Returns `nil` in the `response` parameter, and error information in the `errorInfo` parameter. |

#### Basic usage [#basic-usage-11]

```objc
[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 [#releaselock-1]

#### Description [#description-12]

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.

<CalloutContainer type="warning">
  <CalloutTitle>
    Caution
  </CalloutTitle>

  <CalloutDescription>
    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.
  </CalloutDescription>
</CalloutContainer>

#### Method [#method-12]

You can call the `releaseLock` method as follows:

```objc
- (AgoraRtmErrorCode) destroy;
```

#### Basic usage [#basic-usage-12]

```objc
[stream_channel destroy];
stream_channel = nil;
```

#### Return Value [#return-value-3]

The `releaseLock` method returns an `AgoraRtmErrorCode` data structure. See [Error code](#error-codes-table).

## Topics [#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.

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    Topics only exist in stream channels. Therefore, before using relevant features, you need to create the `AgoraRtmStreamChannel` instance.
  </CalloutDescription>
</CalloutContainer>

AgoraRtmStreamChannel
Stream channel instance

### joinTopic [#jointopic-1]

#### Description [#description-13]

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.

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

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

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](#event-listeners).

#### Method [#method-13]

You can call the `joinTopic` method as follows:

```objc
- (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:<br />- Success: Returns the `AgoraRtmCommonResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- 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`](#enumvmessageqo-s).                                           |
|    `priority`   | `AgoraRtmMessagePriority` | Optional | `AgoraRtmMessagePriorityNormal` | The priority of data transmission in the topic compared to other topics in the same channel. See [`AgoraRtmMessagePriority`](#enumvpriorit-y). |
|      `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 [#basic-usage-13]

```objc
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 [#publishtopicmessage]

#### Description [#description-14]

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](#setup).

#### Method [#method-14]

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

```objc
 // publishTopicMessage[1/2]
- (void) publishTopicMessage:(NSString * _Nonnull)topic
                     message:(NSString * _Nonnull)message
                      option:(AgoraRtmTopicMessageOptions * _Nullable)options
                  completion:(AgoraRtmOperationBlock _Nullable)completionBlock
```

```objc
 // 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:<br />- Success: Returns the `AgoraRtmCommonResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- 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 [#basic-usage-14]

Example 1: Send string messages to a specified channel.

```objc
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.

```objc
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 [#leavetopic-1]

#### Description [#description-15]

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](#event-listeners).

#### Method [#method-15]

You can call the `leaveTopic` method as follows:

```objc
- (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:<br />- Success: Returns the `AgoraRtmCommonResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- Failure: Returns `nil` in the `response` parameter, and error information in the `errorInfo` parameter. |

#### Basic usage [#basic-usage-15]

```objc
[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 [#subscribetopic-1]

#### Description [#description-16]

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](./reference/limitations).

#### Method [#method-16]

You can call the `subscribeTopic` method as follows:

```objc
- (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:<br />- Success: Returns the `AgoraRtmTopicSubscriptionResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- 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&lt;NSString *&gt;` | Optional |    -    | A list of `UserId` of message publishers that you want to subscribe to. If you do not set this property, you can randomly subscribe to up to 64 users by default. |

The `AgoraRtmTopicSubscriptionResponse` data type contains the following properties:

|   Properties   |             Type            | Description                                         |
| :------------: | :-------------------------: | --------------------------------------------------- |
| `succeedUsers` | `NSArray&lt;NSString *&gt;` | A list of successfully subscribed users.            |
|  `failedUsers` | `NSArray&lt;NSString *&gt;` | A list of users that the SDK fails to subscribe to. |

#### Basic usage [#basic-usage-16]

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

```objc
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.

```objc
[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 [#unsubscribetopic-1]

#### Description [#description-17]

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 [#method-17]

You can call the `unsubscribeTopic` method as follows:

```objc
- (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:<br />- Success: Returns the `AgoraRtmCommonResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- 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&lt;NSString *&gt;` | Optional |    -    | A list of `UserId` of message publishers that you want to unsubscribe from. If you do not set this property, you can randomly unsubscribe from up to 64 users by default. |

#### Basic usage [#basic-usage-17]

Example 1: Unsubscribe the specified message publisher in the topic

```objc
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.

```objc
[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 [#messages]

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

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

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

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

AgoraRtmClientKit
Signaling client instance

### publishTopicMessage [#publishtopicmessage-1]

#### Description [#description-18]

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.

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    The following practices can effectively improve the reliability of message transmission:
    <br />- The message payload should be within 32 KB; otherwise, the sending will fail. <br />- 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.
  </CalloutDescription>
</CalloutContainer>

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](#event-listeners).

#### Method [#method-18]

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

```objc
 // publish[1/2]
- (void) publish:(NSString* _Nonnull)channelName
         message:(NSString* _Nonnull)message
          option:(AgoraRtmPublishOptions* _Nullable)publishOption
      completion:(AgoraRtmOperationBlock _Nullable)completionBlock
```

```objc
 // 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:<br />- Success: Returns the `AgoraRtmCommonResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- 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`](#enumvchanneltyp-e). |
|  `customType` |        NSString       | Required |    -    | A user-defined field. Only supports string type.                |

#### Basic usage [#basic-usage-18]

Example 1: Send string messages to a specified channel.

```objc
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.

```objc
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.

```objc
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.

```objc
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);
    }
}];
```

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    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](#event-listeners).
  </CalloutDescription>
</CalloutContainer>

### Receive [#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:

```objc
    @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:

```objc
    @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](#event-listeners).

## Presence [#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.

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    Presence applies to both message channels and stream channels.
  </CalloutDescription>
</CalloutContainer>

AgoraRtmPresence
Presence instance

### getOnlineUsers [#getonlineusers]

#### Description [#description-19]

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 [#method-19]

You can call the `getOnlineUsers` method as follows:

```objc
-(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`](#enumvchanneltyp-e).                                                                                                                                                                                                                      |
|     `options`     | `AgoraRtmGetOnlineUsersOptions` | Optional |    -    | Query options.                                                                                                                                                                                                                                                                       |
| `completionBlock` |  `AgoraRtmGetOnlineUsersBlock`  | Optional |    -    | Callback of invocation result:<br />- Success: Returns the `AgoraRtmGetOnlineUsersResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- 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&lt;AgoraRtmUserState *&gt;` | 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:<br />- A null value indicates that next page does not exist.<br />- 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 [#basic-usage-19]

```objc
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 [#getuserchannels]

#### Description [#description-20]

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 [#method-20]

You can call the `getUserChannels` method as follows:

```objc
-(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:<br />- Success: Returns the `AgoraRtmGetUserChannelsResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- 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&lt;AgoraRtmChannelInfo *&gt;` | 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`](#enumvchanneltyp-e). |

#### Basic usage [#basic-usage-20]

```objc
[[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 [#setstate]

#### Description [#description-21]

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 [#method-21]

You can call the `setState` method as follows:

```objc
-(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`](#enumvchanneltyp-e).                                                                                                                                                                                                              |
|      `items`      |       NSDictionary       | Required |    -    | User state, an array of `StateItem`.                                                                                                                                                                                                                                         |
| `completionBlock` | `AgoraRtmOperationBlock` | Optional |    -    | Callback of invocation result:<br />- Success: Returns the `AgoraRtmCommonResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- Failure: Returns `nil` in the `response` parameter, and error information in the `errorInfo` parameter. |

#### Basic usage [#basic-usage-21]

```objc
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 [#getstate]

#### Description [#description-22]

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

#### Method [#method-22]

You can call the `getState` method as follows:

```objc
-(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`](#enumvchanneltyp-e).                                                                                                                                                                                                                        |
|      `userId`     |             NSString            | Required |    -    | User ID.                                                                                                                                                                                                                                                                               |
| `completionBlock` | `AgoraRtmPresenceGetStateBlock` | Optional |    -    | Callback of invocation result:<br />- Success: Returns the `AgoraRtmPresenceGetStateResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- 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 [#basic-usage-22]

```objc
[[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 [#removestate]

#### Description [#description-23]

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](#event-listeners).

#### Method [#method-23]

You can call the `removeState` method as follows:

```objc
-(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`](#enumvchanneltyp-e).                                                                                                                                                                                                              |
|       `keys`      | `NSArray&lt;NSString *&gt;` | 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:<br />- Success: Returns the `AgoraRtmCommonResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- Failure: Returns `nil` in the `response` parameter, and error information in the `errorInfo` parameter. |

#### Basic usage [#basic-usage-23]

```objc
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 [#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 [#setchannelmetadata]

#### Description [#description-24]

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

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

After successfully setting channel metadata, users who subscribe to the channel and enable event listeners can receive the `AgoraRtmStorageTypeChannel` type of the `didReceiveStorageEvent` event notification. See [Event listeners](#event-listeners).

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

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

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

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

#### Method [#method-24]

You can call the `setChannelMetadata` method as follows:

```objc
- (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`](#enumvchanneltyp-e).                                                                                                                                                                                                              |
|       `data`      |     `AgoraRtmMetadata`    | Required |        -        | Metadata item. See [`AgoraRtmMetadata`](#storagemetadat-a).                                                                                                                                                                                                                  |
|     `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:<br />- Success: Returns the `AgoraRtmCommonResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- 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 [#basic-usage-24]

```objc
 //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 [#getchannelmetadata]

#### Description [#description-25]

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

#### Method [#method-25]

You can call the `getChannelMetadata` method as follows:

```objc
- (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`](#enumvchanneltyp-e).                                                                                                                                                                                                                   |
| `completionBlock` | `AgoraRtmGetMetadataBlock` | Optional |    -    | Callback of invocation result:<br />- Success: Returns the `AgoraRtmGetMetadataResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- 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`](#storagemetadat-a). |

#### Basic usage [#basic-usage-25]

```objc
[[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 [#removechannelmetadata]

#### Description [#description-26]

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](#event-listeners).

#### Method [#method-26]

You can call the `removeChannelMetadata` method as follows:

```objc
- (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`](#enumvchanneltyp-e).                                                                                                                                                                                                              |
|       `data`      |     `AgoraRtmMetadata`    | Required |        -        | Metadata item. See [`AgoraRtmMetadata`](#storagemetadat-a).                                                                                                                                                                                                                  |
|     `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:<br />- Success: Returns the `AgoraRtmCommonResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- 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 [#basic-usage-26]

```objc
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 [#updatechannelmetadata]

#### Description [#description-27]

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](#event-listeners).

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    You cannot use this method to update metadata items which do not exist.
  </CalloutDescription>
</CalloutContainer>

#### Method [#method-27]

You can call the `updateChannelMetadata` method as follows:

```objc
- (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`](#enumvchanneltyp-e).                                                                                                                                                                                                              |
|       `data`      |     `AgoraRtmMetadata`    | Required |        -        | Metadata item. See [`AgoraRtmMetadata`](#storagemetadat-a).                                                                                                                                                                                                                  |
|     `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:<br />- Success: Returns the `AgoraRtmCommonResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- 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 [#basic-usage-27]

```objc
// 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 [#setusermetadata]

#### Description [#description-28]

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

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

After successfully setting user metadata, users who subscribe to the user and enable event listeners can receive the `AgoraRtmStorageTypeUser` type of the `didReceiveStorageEvent` event notification. See [Event listeners](#event-listeners).

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

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

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

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

#### Method [#method-28]

You can call the `setUserMetadata` method as follows:

```objc
- (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`](#storagemetadat-a).                                                                                                                                                                                                                  |
|     `options`     | `AgoraRtmMetadataOptions` | Optional |               -              | Options for setting the channel metadata.                                                                                                                                                                                                                                    |
| `completionBlock` |  `AgoraRtmOperationBlock` | Optional |               -              | Callback of invocation result:<br />- Success: Returns the `AgoraRtmCommonResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- 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 [#basic-usage-28]

```objc
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 [#getusermetadata]

#### Description [#description-29]

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

#### Method [#method-29]

You can call the `getUserMetadata` method as follows:

```objc
- (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:<br />- Success: Returns the `AgoraRtmGetMetadataResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- 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`](#storagemetadat-a). |

#### Basic usage [#basic-usage-29]

```objc
[[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 [#removeusermetadata]

#### Description [#description-30]

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](#event-listeners).

#### Method [#method-30]

You can call the `removeUserMetadata` method as follows:

```objc
- (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`](#storagemetadat-a).                                                                                                                                                                                                                  |
|     `options`     | `AgoraRtmMetadataOptions` | Optional |               -              | Options for setting the channel metadata.                                                                                                                                                                                                                                    |
| `completionBlock` |  `AgoraRtmOperationBlock` | Optional |               -              | Callback of invocation result:<br />- Success: Returns the `AgoraRtmCommonResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- 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 [#basic-usage-30]

```objc
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 [#updateusermetadata]

#### Description [#description-31]

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](#event-listeners).

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    You cannot use this method to update metadata items which do not exist.
  </CalloutDescription>
</CalloutContainer>

#### Method [#method-31]

You can call the `updateUserMetadata` method as follows:

```objc
- (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`](#storagemetadat-a).                                                                                                                                                                                                                  |
|     `options`     | `AgoraRtmMetadataOptions` | Optional |               -              | Options for setting the channel metadata.                                                                                                                                                                                                                                    |
| `completionBlock` |  `AgoraRtmOperationBlock` | Optional |               -              | Callback of invocation result:<br />- Success: Returns the `AgoraRtmCommonResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- 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 [#basic-usage-31]

```objc
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 [#subscribeusermetadata]

#### Description [#description-32]

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](#event-listeners).

#### Method [#method-32]

You can call the `subscribeUserMetadata` method as follows:

```objc
- (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:<br />- Success: Returns the `AgoraRtmCommonResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- Failure: Returns `nil` in the `response` parameter, and error information in the `errorInfo` parameter. |

#### Basic usage [#basic-usage-32]

```objc
[[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 [#unsubscribeusermetadata]

#### Description [#description-33]

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

#### Method [#method-33]

You can call the `unsubscribeUserMetadata` method as follows:

```objc
- (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:<br />- Success: Returns the `AgoraRtmCommonResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- Failure: Returns `nil` in the `response` parameter, and error information in the `errorInfo` parameter. |

#### Basic usage [#basic-usage-33]

```objc
[[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 [#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:<br />- `-1`: Disable the version verification.<br />- > `0`: Enable the version verification. The operation can only be performed if the target version number matches this value. |
|     `items`     | `NSArray&lt;AgoraRtmMetadataItem *&gt;` | 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`  | <br />- Returns the real version number in read operations.<br />- Serves as a version control switch in write operations:<br />- `-1`: Disable the version verification. <br />- > `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 [#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.

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    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.
  </CalloutDescription>
</CalloutContainer>

AgoraRtmLock
Lock instance

### setLock [#setlock]

#### Description [#description-34]

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](#event-listeners).

#### Method [#method-34]

You can call the `setLock` method as follows:

```objc
-(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`](#enumvchanneltyp-e).                                                                                                                                                                                                                                                                                                         |
|     `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:<br />- Success: Returns the `AgoraRtmCommonResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- Failure: Returns `nil` in the `response` parameter, and error information in the `errorInfo` parameter.                                                                                            |

#### Basic usage [#basic-usage-34]

```objc
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 [#acquirelock]

#### Description [#description-35]

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](#event-listeners).

#### Method [#method-35]

You can call the `acquireLock` method as follows:

```objc
-(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`](#enumvchanneltyp-e).                                                                                                                                                                                                              |
|     `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:<br />- Success: Returns the `AgoraRtmCommonResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- Failure: Returns `nil` in the `response` parameter, and error information in the `errorInfo` parameter. |

#### Basic usage [#basic-usage-35]

```objc
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 [#releaselock-2]

#### Description [#description-36]

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](#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 [#method-36]

You can call the `releaseLock` method as follows:

```objc
-(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`](#enumvchanneltyp-e).                                                                                                                                                                                                              |
|     `lockName`    |         NSString         | Required |    -    | Lock name.                                                                                                                                                                                                                                                                   |
| `completionBlock` | `AgoraRtmOperationBlock` | Optional |    -    | Callback of invocation result:<br />- Success: Returns the `AgoraRtmCommonResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- Failure: Returns `nil` in the `response` parameter, and error information in the `errorInfo` parameter. |

####

Basic usage

```objc
[[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 [#revokelock]

#### Description [#description-37]

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](#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 [#method-37]

You can call the `revokeLock` method as follows:

```objc
-(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`](#enumvchanneltyp-e).                                                                                                                                                                                                              |
|     `lockName`    |         NSString         | Required |    -    | Lock name.                                                                                                                                                                                                                                                                   |
|      `userId`     |         NSString         | Required |    -    | The ID of the user who has a lock.                                                                                                                                                                                                                                           |
| `completionBlock` | `AgoraRtmOperationBlock` | Optional |    -    | Callback of invocation result:<br />- Success: Returns the `AgoraRtmCommonResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- Failure: Returns `nil` in the `response` parameter, and error information in the `errorInfo` parameter. |

#### Basic usage [#basic-usage-36]

```objc
[[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 [#getmessages]

#### Description [#description-38]

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 [#method-38]

You can call the `getMessages` method as follows:

```objc
-(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`](#enumvchanneltyp-e).                                                                                                                                                                                                                |
| `completionBlock` | `AgoraRtmGetLocksBlock` | Optional |    -    | Callback of invocation result:<br />- Success: Returns the `AgoraRtmGetLocksResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- 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&lt;AgoraRtmLockDetail *&gt;` | 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 [#basic-usage-37]

```objc
[[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 [#removelock]

#### Description [#description-39]

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](#event-listeners).

#### Method [#method-39]

You can call the `removeLock` method as follows:

```objc
-(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`](#enumvchanneltyp-e).                                                                                                                                                                                                              |
|     `lockName`    |         NSString         | Required |    -    | Lock name.                                                                                                                                                                                                                                                                   |
| `completionBlock` | `AgoraRtmOperationBlock` | Optional |    -    | Callback of invocation result:<br />- Success: Returns the `AgoraRtmCommonResponse` data in the `response` parameter, and `nil` in the `errorInfo` parameter.<br />- Failure: Returns `nil` in the `response` parameter, and error information in the `errorInfo` parameter. |

#### Basic usage [#basic-usage-38]

```objc
[[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 [#enumerated-types]

### Enum [#enum]

#### AgoraRtmAreaCode [#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 [#agorartmchanneltype]

Channel types.

|             Value            | Description           |
| :--------------------------: | --------------------- |
| `AgoraRtmChannelTypeMessage` | `1`: Message channel. |
|  `AgoraRtmChannelTypeStream` | `2`: Stream channel.  |
|   `AgoraRtmChannelTypeUser`  | `3`: User Channel.    |

#### AgoraRtmClientConnectionChangeReason [#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 [#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 [#agorartmencryptionmode]

Encryption mode.

|             Value             | Description            |
| :---------------------------: | ---------------------- |
|    `AgoraRtmEncryptionNone`   | `0`: No encryption.    |
| `AgoraRtmEncryptionAES128GCM` | `1`: AES-128-GCM mode. |
| `AgoraRtmEncryptionAES256GCM` | `2`: AES-256-GCM mode. |

#### AgoraRtmJoinChannelFeature [#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 &lt;&lt; 1`: Sets the storage event notification.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
|   `AgoraRtmJoinChannelFeatureLock`   | `1 &lt;&lt; 2`: Sets the lock event notification.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
|  `AgoraRtmJoinChannelFeatureBeQuiet` | `1 &lt;&lt; 3`: Sets the silent mode. In this mode, the SDK behaves as follows:<br />- You still receive event notifications from other users.<br />- 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.<br />- When calling the `getOnlineUsers` method, your information is not included.<br />- When calling the `getUserChannels` method, the channels that you subscribe to in silent mode are not included. |

#### AgoraRtmLockEventType [#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 [#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 [#agorartmmessagepriority]

Message priority.

|               Value              | Description   |
| :------------------------------: | ------------- |
| `AgoraRtmMessagePriorityHighest` | `0`: Highest. |
|   `AgoraRtmMessagePriorityHigh`  | `1`: High.    |
|  `AgoraRtmMessagePriorityNormal` | `4`: Normal.  |
|   `AgoraRtmMessagePriorityLow`   | `8`: Low.     |

#### AgoraRtmMessageQos [#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 [#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 [#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 [#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 [#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 [#agorartmprotocoltype]

Protocol type.

|             Value             | Description                      |
| :---------------------------: | -------------------------------- |
|  `AgoraRtmProtocolTypeTcpUdp` | `0`: Both TCP and UDP protocols. |
| `AgoraRtmProtocolTypeTcpOnly` | `1`: Only TCP protocol.          |

#### AgoraRtmServiceType [#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.                                                                                 |

<CalloutContainer type="info">
  <CalloutTitle>
    Information
  </CalloutTitle>

  <CalloutDescription>
    To fully utilize all services offered by Signaling, use bitwise operations to simultaneously configure two service types.
  </CalloutDescription>
</CalloutContainer>

#### AgoraRtmProxyType [#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 [#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 [#agorartmstoragetype]

Storage type.

|             Value            | Description                  |
| :--------------------------: | ---------------------------- |
|   `AgoraRtmStorageTypeUser`  | `1`: User metadata event.    |
| `AgoraRtmStorageTypeChannel` | `2`: Channel metadata event. |

#### AgoraRtmSubscribeChannelFeature [#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 &lt;&lt; 1`: Sets the storage event notification.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
|  `AgoraRtmSubscribeChannelFeatureMessage` | `1 &lt;&lt; 2`: Sets the message event notification.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
|   `AgoraRtmSubscribeChannelFeatureLock`   | `1 &lt;&lt; 3`: Sets the lock event notification.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
|  `AgoraRtmSubscribeChannelFeatureBeQuiet` | `1 &lt;&lt; 4`: Sets the silent mode. In this mode, the SDK behaves as follows:<br />- You still receive event notifications from other users.<br />- 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.<br />- When calling the `getOnlineUsers` method, your information is not included.<br />- When calling the `getUserChannels` method, the channels that you subscribe to in silent mode are not included. |

#### AgoraRtmTopicEventType [#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 [#troubleshooting]

Refer to the following information for troubleshooting API calls.

#### ErrorInfo [#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).

#### 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: <br /> - Check that the App ID is correct. <br /> - Ensure that Signaling has been activated for the App ID.                                                                                                                                                                                                                                |
| `-10005`   | `AgoraRtmErrorInvalidToken`                         | Invalid Token: <br /> - The token is invalid, check whether the Token Provider generates a valid Signaling Token.                                                                                                                                                                                                                                           |
| `-10006`   | `AgoraRtmErrorInvalidUserId`                        | Invalid User ID: <br /> - Check if user ID is empty. <br /> - 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: <br /> - Check if the channel name is empty. <br /> - 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: <br /> - Check tha Signaling is activated on your App ID. <br /> - Check if the token or `userId` is banned.                                                                                                                                                                                                              |
| `-10013`   | `AgoraRtmErrorLoginAborted`                         | SDK login interrupted due to unknown problem: <br /> - Check that the current network is stable and switch to a stable network environment. <br /> - 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: <br /> - `AgoraRtmChannelTypeMessage`: Message Channel <br /> - `AgoraRtmChannelTypeStream`: Stream Channel <br /> - `AgoraRtmChannelTypeUser`: User Channel                                                                                         |
| `-10020`   | `AgoraRtmErrorInvalidEncryptionParameter`           | Message encryption parameters are invalid. <br />- Check that the encryption key generated is a String. <br />- Check that the generated encryption salt is `Uint8Array` type and that the length is 32 bytes. <br />- 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: <br />- 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. <br />- 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: <br /> - The user is not online, offline or has not joined the channel<br /> - Check for typos in `userId`.                                                                                                                                                                                                            |
| `-11002`   | `AgoraRtmErrorChannelNotSubscribed`                 | The user has not subscribed to the channel: <br /> - The user is not online, offline or has not joined the channel<br /> - 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](/en/realtime-media/rtm/reference/limitations) 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: <br /> - Check if the number of joined channels exceeds the limit. <br /> - Check if the channel name is illegal. <br /> - Check if the network is disconnected.                                                                                                                                                               |
| `-11008`   | `AgoraRtmErrorChannelInvalidTopicName`              | Invalid topic name: <br /> - Check whether the topic name contains illegal characters. <br /> - 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: <br /> - Message Channel single message package limit is 32 KB. <br /> - Stream Channel single message package limit is 1 KB.                                                                                                                                           |
| `-11011`   | `AgoraRtmErrorChannelInvalidUserList`               | Invalid user list: <br /> - Check if the user list is empty. <br /> - Check if the user list contains invalid entries.                                                                                                                                                                                                                                      |
| `-11012`   | `AgoraRtmErrorChannelNotAvailable`                  | Invalid user list: <br /> - Check if the user list is empty<br /> - 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: <br /> - Check that the `cipherKey` is valid. <br /> - Check that the `salt` is valid. <br /> - 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: <br /> - Check if the user ID set when calling the method is correct.<br /> - 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](/en/realtime-media/rtm/reference/limitations) for details.                                                                                                                                                                                             |
| `-13005`   | `AgoraRtmErrorPresenceStateCountOverflow`           | The number of temporary user state key/value pairs exceeds the limit. See [API usage limits](/en/realtime-media/rtm/reference/limitations) 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.                                                                                                                                                                                                                                                                                                                              |
