Integrate the iOS SDK

更新时间:
复制 MD 格式

Interactive Message enhances communication and engagement in live streaming rooms. The SDK lets you add comments, bullet comments, and likes to your live streaming application.

Prerequisites

Before you integrate the client-side SDK, complete the server-side integration and ensure an endpoint is available for the client to get an authentication token. For instructions, see Server-side integration.

Environment requirements

  • Xcode 12.0 or later. We recommend that you use the latest official version.

  • CocoaPods 1.9.3 or later.

  • iOS 10.0 or later for on-device debugging.

Integrate the SDK

  1. In your Podfile, add the following dependency:

    # Replace x.y.z with the specific SDK version, such as 1.9.0.
    # You can find the latest version number in the release notes.
    pod 'AliVCInteractionMessage', '~> x.y.z'
  2. Run pod install --repo-update.

Use the SDK

Use the SDK in the following sequence:

  1. Initialization

  2. Login

  3. Operations

  4. Logout

  5. Deinitialization

  6. Others

Operations

  • Group operations

    • Create group (requires login as an admin)

    • Close group (only for the group owner or an admin)

    • Join group

    • Leave group

    • Query group info

    • Modify group info (only for the group owner or an admin)

    • List recent group members

    • List all group members (only for the group owner or an admin)

    • Mute group (only for the group owner or an admin)

    • Unmute group (only for the group owner or an admin)

    • Mute users in group (only for the group owner or an admin)

    • Unmute users in group (only for the group owner or an admin)

    • List muted users in group (only for the group owner or an admin)

  • Message operations

    • Send a C2C message

    • Send a group message

    • List recent group messages

    • List all group messages (only for the group owner or an admin)

    • Delete/recall group message

    • Query message history

Import the header file

Import the header file before calling the API.

#import <AliVCInteractionMessage/AliVCInteractionMessage.h>

Initialization

Initialize the SDK at the main entry point of the relevant module before calling any other APIs.

Code

// Initialize with setup.
AliVCIMEngineConfig *config = [AliVCIMEngineConfig new];
config.deviceId = @"xxxx";   // The device ID. You can obtain it using this system method: [[UIDevice currentDevice] identifierForVendor].UUIDString;
config.appId = @"APP_ID";    // [Required] If left empty, initialization fails with error code -2. After creating your application, replace APP_ID in this example with your AppId. Otherwise, you cannot use the service.
config.appSign = @"APP_SIGN"; // [Required] If left empty, initialization fails with error code -2. After creating your application, replace APP_SIGN in this example with your AppSign. Otherwise, you cannot use the service.
config.logLevel = AliVCIMLogLevelDebug; // Set this during debugging.
int ret = [[AliVCIMEngine sharedEngine] setup:config]; // A non-zero return value indicates that initialization has failed. Common error codes: 1001 for repeated initialization, 1002 for a failure to create the underlying engine, -1 for repeated underlying initialization, and -2 for invalid configuration.
NSLog(@"API - setup result: %d", ret);


// Add a listener.
[[AliVCIMEngine sharedEngine] addListener:self];


// Handle callback events: AliVCIMEngineListenerProtocol
- (void)onIMEngineConnecting {
    NSLog(@"Event - onIMEngineConnecting");
}

- (void)onIMEngineConnectSuccess {
    NSLog(@"Event - onIMEngineConnectSuccess");
}

- (void)onIMEngineConnectFailed:(NSError *)error {
    NSLog(@"Event - onIMEngineConnectFailed error: %@", error);
}

- (void)onIMEngineDisconnect:(AliVCIMEngineDisconnectType)type {
    NSLog(@"Event - onIMEngineDisconnect: %d", type);
}

- (void)onIMEngineTokenExpired:(AliVCIMFetchAuthTokenBlock)fetchAuthTokenBlock {
    NSLog(@"Event - onIMEngineTokenExpired");
    // This requires server-side integration. You need to provide an endpoint for the client to get authentication information. The client then uses this endpoint to get the nonce and token.
    if (fetchAuthTokenBlock) {
        AliVCIMAuthToken *auth = [AliVCIMAuthToken new];
        auth.timestamp = 22123123;  // The timestamp value returned by the server.
        auth.nonce = @"xxx";        // The nonce value returned by the server.
        auth.role = @"admin";       // The admin role, which can create or close groups. Set this to an empty string if not needed.
        auth.token = @"xxx"         // The token value returned by the server.
            fetchAuthTokenBlock(auth, nil);
    }
}

/**
 * Starting from v1.4.1, a callback for connection states is added. There are four states:
 * AliVCIMEngineLinkState_idle: The initial state before login.
 * AliVCIMEngineLinkState_connecting: The state during login or reconnection after a disconnection.
 * AliVCIMEngineLinkState_connected: The state after a successful login or reconnection.
 * AliVCIMEngineLinkState_disconnected: The state after being disconnected due to network issues or other exceptions.
 * 
 * Use these state changes to provide relevant user feedback. For example, when the state changes from connected to disconnected, prompt the user to check their network connection.
 */
-(void)onIMEngineLinkStateEvent:(AliVCIMLinkStateEvent *)event {
    AVLOG(@"Event - onIMEngineLinkStateEvent: %@", event);

}

Login

Log in with authentication credentials (timestamp, nonce, and token) obtained from your server.

Code

AliVCIMUser *user = [AliVCIMUser new];
user.userId = @"abc";  // The ID of the currently logged-in user. Must be 64 characters or less and contain only uppercase letters (A-Z), lowercase letters (a-z), digits (0-9), and hyphens (-).
user.userExtension = @"{}"; // Extended user information, such as an avatar or nickname, encapsulated as a JSON string.
AliVCIMAuthToken *auth = [AliVCIMAuthToken new];
auth.timestamp = 122222; // The timestamp value returned by the server.
auth.nonce = @"xxx";     // The nonce value returned by the server.
auth.role = @"admin";    // The admin role, which can create or close groups. Set this to an empty string if not needed.
auth.token = @"xxx";     // The token value returned by the server.
AliVCIMLoginReq *req = [AliVCIMLoginReq new];
req.currentUser = user;
req.authToken = auth;
[[AliVCIMEngine sharedEngine] login:req completed:^(NSError * _Nullable error) {
    NSLog(@"API - login result: %@", error ? error.description : @"success");
    if (!error) {
        // Login successful.
    }
}];

Group operations

Get the group manager

// Ensure the SDK is initialized; otherwise, this returns null.
AliVCIMGroupManager *groupManager = [[AliVCIMEngine sharedEngine] getGroupManager];

Add and remove the group listener

// Add the group event listener at an appropriate time, for example, after entering a room and completing login.
[[[AliVCIMEngine sharedEngine] getGroupManager] addListener:self];

// Remove the listener when it is no longer needed.
[[[AliVCIMEngine sharedEngine] getGroupManager] removeListener:self];

// Handle group events: AliVCIMGroupListenerProtocol
- (void)imGroup:(NSString *)groupId onJoined:(AliVCIMUser *)user {
    // A user has joined the group.
    NSLog(@"Event - imGroup:%@ onJoin: %@", groupId, user);
}

- (void)imGroup:(NSString *)groupId onLeaved:(AliVCIMUser *)user {
    // A user has left the group.
    NSLog(@"Event - imGroup:%@ onLeave: %@", groupId, user);
}

- (void)imGroup:(NSString *)groupId onExited:(int)reason {
    // The group has been closed.
    NSLog(@"Event - imGroup:%@ onExited: %d", groupId, reason);
}

- (void)imGroup:(NSString *)groupId onInfoChanged:(AliVCIMGroupInfoStatus *)status {
    // The group information has changed.
    NSLog(@"Event - imGroup:%@ onInfoChanged: %@", groupId, status);
}

- (void)imGroup:(NSString *)groupId onMuteChanged:(AliVCIMGroupMuteStatus *)status {
    // The mute status of the group has changed.
    NSLog(@"Event - imGroup:%@ onMuteChanged: %@", groupId, status);
}

/**
 Group member change
 Added in v1.4.1. If you override this interface, the old interface will no longer be called back. Make sure to migrate the old logic.
 @param info Information about the change in group members.
 */
- (void)imOnGroupMemberChanged:(AliVCImGroupMemberChangeInfo *)info {
    AVLOG(@"Event - imOnGroupMemberChanged:%@", info.description);
}

Create a group

You must be logged in as an admin to call this method.

Note

You can create a maximum of 5,000 groups. Closed groups do not count toward this limit. To ensure efficient resource utilization, close groups that are no longer needed.

AliVCIMCreateGroupReq *req = [AliVCIMCreateGroupReq new];
req.groupId = nil;   // The group ID. If this is empty, the system creates a new group and returns a unique ID. If it is not empty, the groupId can be up to 64 characters long and can only contain uppercase letters (A-Z), lowercase letters (a-z), digits (0-9), and hyphens (-). It cannot contain other characters.
req.groupName = @"xxx"; // The group name. This must be set, otherwise the call will fail.
req.groupMeta = @"xxx"; // Extended group information. If there are multiple fields, consider encapsulating them as a JSON string.
[[[AliVCIMEngine sharedEngine] getGroupManager] createGroup:req completed:^(AliVCIMCreateGroupRsp * _Nullable rsp, NSError * _Nullable error) {
    if (rsp) {
        // Success.
        NSLog(@"API - createGroup rsp: %@", rsp);
    }
}];

Close a group

Only the group owner or an admin can call this method.

AliVCIMCloseGroupReq *req = [AliVCIMCloseGroupReq new];
req.groupId = @"xxx";  // The group ID.
[[[AliVCIMEngine sharedEngine] getGroupManager] closeGroup:req completed:^(NSError * _Nullable error) {
    
}];

Join a group

AliVCIMJoinGroupReq *req = [AliVCIMJoinGroupReq new];
req.groupId = @"xxx";  // The group ID.
[[[AliVCIMEngine sharedEngine] getGroupManager] joinGroup:req completed:^(AliVCIMJoinGroupRsp * _Nullable rsp, NSError * _Nullable error) {
    if (rsp) {
        // Success.
        NSLog(@"API - joinGroup rsp: %@", rsp);
    }
}];

Leave a group

AliVCIMLeaveGroupReq *req = [AliVCIMLeaveGroupReq new];
req.groupId = @"xxx";  // The group ID.
[[[AliVCIMEngine sharedEngine] getGroupManager] leaveGroup:req completed:^(NSError * _Nullable error) {

}];

Query group information

AliVCIMQueryGroupReq *req = [AliVCIMQueryGroupReq new];
req.groupId = @"xxx";  // The group ID.
[[[AliVCIMEngine sharedEngine] getGroupManager] queryGroup:req completed:^(AliVCIMQueryGroupRsp * _Nullable rsp, NSError * _Nullable error) {
    if (rsp) {
        // Success.
        NSLog(@"API - queryGroup rsp: %@", rsp);
    }
}];

Modify group information

Only the group owner or an admin can call this method to modify extended group information or set admins.

AliVCIMModifyGroupReq *req = [AliVCIMModifyGroupReq new];
req.groupId = @"xxx";  // The group ID.
req.groupMeta = @"xxx";  // Add extended group information. To clear it, do not set this parameter and set req.forceUpdateGroupMeta=YES.
req.admins = @[@"xxx"];  // Specify a list of admin IDs. You can set a maximum of 3 admins. To clear the list, do not set this parameter and set req.forceUpdateAdmins=YES.
[[[AliVCIMEngine sharedEngine] getGroupManager] modifyGroup:req completed:^(NSError * _Nullable error) {

}];

List recent group members

Important

If the current group is a super large group, this API call is unavailable.

/**
 * You need to check if the current group is a super large group. If it is, this API is unavailable.
 * 1. If AliVCIMGroupInfo.isBigGroup returns true after a successful group join, the group is a super large group.
 * 2. If you join a group that is not a super large group, it may become one as more members join.
 * 3. Listen for group status changes. If AliVCImGroupMemberChangeInfo.isBigGroup returned by AliVCIMGroupListenerProtocol#imOnGroupMemberChanged() is true, the group is a super large group.
 */
AliVCIMListRecentGroupUserReq *req = [AliVCIMListRecentGroupUserReq new];
req.groupId = @"xxx";  // The group ID.
[[[AliVCIMEngine sharedEngine] getGroupManager] listRecentGroupUser:req completed:^(AliVCIMListRecentGroupUserRsp * _Nullable rsp, NSError * _Nullable error) {
    if (rsp) {
        // Success.
        NSLog(@"API - listRecentGroupUser rsp: %@", rsp);
    }
}];

List all group members

Important
  • If the current group is a super large group, you cannot query the user list, and this API call is unavailable.

  • Only the group owner or an admin can call this method.

/**
 * You need to check if the current group is a super large group. If it is, this API is unavailable.
 * 1. If AliVCIMGroupInfo.isBigGroup returns true after a successful group join, the group is a super large group.
 * 2. If you join a group that is not a super large group, it may become one as more members join.
 * 3. Listen for group status changes. If AliVCImGroupMemberChangeInfo.isBigGroup returned by AliVCIMGroupListenerProtocol#imOnGroupMemberChanged() is true, the group is a super large group.
 */
AliVCIMListGroupUserReq *req = [AliVCIMListGroupUserReq new];
req.groupId = @"xxx";  // The group ID.
req.nextPageToken = @"xxx";  // If not provided, it indicates the first page. The server returns the next page token for traversal, which the client should include when fetching the next page.
req.pageSize = 10;
req.sortType = AliVCIMSortType_ASC;
[[[AliVCIMEngine sharedEngine] getGroupManager] listGroupUser:req completed:^(AliVCIMListGroupUserRsp * _Nullable rsp, NSError * _Nullable error) {
    if (rsp) {
        // Success.
        NSLog(@"API - listGroupUser rsp: %@", rsp);
    }
}];

Mute a group

Only the group owner or an admin can call this method.

AliVCIMMuteAllReq *req = [AliVCIMMuteAllReq new];
req.groupId = @"xxx";  // The group ID.
[[[AliVCIMEngine sharedEngine] getGroupManager] muteAll:req completed:^(NSError * _Nullable error) {

}];

Unmute a group

Only the group owner or an admin can call this method.

AliVCIMCancelMuteAllReq *req = [AliVCIMCancelMuteAllReq new];
req.groupId = @"xxx";  // The group ID.
[[[AliVCIMEngine sharedEngine] getGroupManager] cancelMuteAll:req completed:^(NSError * _Nullable error) {

}];

Mute users in a group

Only the group owner or an admin can call this method.

AliVCIMMuteUserReq *req = [AliVCIMMuteUserReq new];
req.groupId = @"xxx";  // The group ID.
req.userList = @[@"xxx"]; // A list of user IDs to mute.
[[[AliVCIMEngine sharedEngine] getGroupManager] muteUser:req completed:^(NSError * _Nullable error) {

}];

Unmute users in a group

Only the group owner or an admin can call this method.

AliVCIMCancelMuteUserReq *req = [AliVCIMCancelMuteUserReq new];
req.groupId = @"xxx";  // The group ID.
req.userList = @[@"xxx"]; // A list of user IDs to unmute.
[[[AliVCIMEngine sharedEngine] getGroupManager] cancelMuteUser:req completed:^(NSError * _Nullable error) {

}];

List muted users in a group

Only the group owner or an admin can call this method.

AliVCIMListMuteUsersReq *req = [AliVCIMListMuteUsersReq new];
req.groupId = @"xxx";  // The group ID.
[[[AliVCIMEngine sharedEngine] getGroupManager] listMuteUsers:req completed:^(AliVCIMListMuteUsersRsp * _Nullable rsp, NSError * _Nullable error) {
    if (rsp) {
        // Success.
        NSLog(@"API - listMuteUsers rsp: %@", rsp);
    }
}];

Message operations

Get the message manager

// You must ensure that the SDK has been initialized, otherwise this will return null.
AliVCIMMessageManager *messageManager = [[AliVCIMEngine sharedEngine] getMessageManager];

Add and remove the message listener

// Add the message event listener at an appropriate time, for example, after entering a room and completing login.
[[[AliVCIMEngine sharedEngine] getMessageManager] addListener:self];

// Remove the listener when it is no longer needed.
[[[AliVCIMEngine sharedEngine] getMessageManager] removeListener:self];

// Handle message events: AliVCIMMessageListenerProtocol
- (void)onIMReceivedC2CMessage:(AliVCIMMessage *)message {
    // Received a C2C message from another user.
    NSLog(@"Event - onIMReceivedC2CMessage: %@", message);
}

- (void)onIMReceivedGroupMessage:(AliVCIMMessage *)message {
    // Received a group message.
    NSLog(@"Event - onIMReceivedGroupMessage: %@", message);
}

- (void)onIMDeleteMessage:(NSString *)messageId groupId:(NSString *)groupId {
    // A message has been recalled or deleted.
    NSLog(@"Event - onIMDeleteMessage:%@ groupId: %@", messageId, groupId);

Send a C2C message

AliVCIMSendMessageToUserReq *req = [AliVCIMSendMessageToUserReq new];
req.reveiverId = @"xxx";   // The receiver's ID. Ensure the user is online; otherwise, error code 424 is returned. Resend the message after the user comes online.
req.data = @"xxx";         // The message content. For structured data, consider using a JSON string.
req.type = 88888;          // Custom message type. Must be greater than 10000.
req.skipAudit = YES;       // Skip security review. If YES, the message is not reviewed by the Alibaba Cloud security review service. If NO, the message is reviewed, and if the review fails, the message is not sent.
req.level =  AliVCIMMessageLevel_Normal; // The message level. For high reliability, use AliVCIMMessageLevel_High.
[[[AliVCIMEngine sharedEngine] getMessageManager] sendC2CMessage:req completed:^(AliVCIMSendMessageToUserRsp * _Nullable rsp, NSError * _Nullable error) {
    if (rsp) {
        // Success.
        NSLog(@"API - sendC2CMessage rsp: %@", rsp);
    }
}];

Send a group message

// Ensure you have successfully joined the group (after the joinGroup callback succeeds) before sending a group message. Otherwise, error code 425 is returned.
// Starting from v1.9.0, AliVCIMSendMessageToGroupReq#noStorage is deprecated. If you are using it, you must upgrade. Configure storage options through AliVCIMSendMessageToGroupReq#messageOption.
// Starting from v1.9.0, message storage and caching can be configured independently through AliVCIMSendMessageToGroupReq#messageOption. Configure them according to your needs.
AliVCIMSendMessageToGroupReq *req = [AliVCIMSendMessageToGroupReq new];
req.groupId = @"xxx";     // The group ID.
req.data = @"xxx";        // The message content. For structured data, consider using a JSON string.
req.type = 99999;         // Custom message type. Must be greater than 10000.
req.skipMuteCheck = YES;  // Skip mute check. If YES, allows muted users to send messages.
req.skipAudit = YES;      // Skip security review. If YES, the message is not reviewed by the Alibaba Cloud security review service. If NO, the message is reviewed, and if the review fails, the message is not sent.
req.level =  AliVCIMMessageLevel_Normal; // Set the message level. The default is AliVCIMMessageLevel_Normal. For more information, see the "Message Level Throttling" section.
req.messageOption = [AliVCIMSendMessageOption new];
req.messageOption.isStorageEnable = NO; // Specifies whether to store the message (default: NO). If enabled, sent messages are stored in the database and will be returned when you query history messages or list messages.
req.messageOption.isCacheEnable = NO; // Specifies whether to cache the message (default: NO). If enabled, sent messages are cached in memory (note: only the 50 most recent messages are cached) and will be returned when you list recent messages.
req.repeatCount = 1; // Sets the message's repeat count. The default is 1. This is mainly used to aggregate messages of the same type, such as likes. You can aggregate n likes and then send one message by setting repeatCount to n.
[[[AliVCIMEngine sharedEngine] getMessageManager] sendGroupMessage:req completed:^(AliVCIMSendMessageToGroupRsp * _Nullable rsp, NSError * _Nullable error) {
    if (rsp) {
        // Success.
        NSLog(@"API - sendGroupMessage rsp: %@", rsp);
    }
}];

You can set the message level by using req.level. The default is AliVCIMMessageLevel_Normal. For details, see More Information.

Delete or recall a group message

AliVCIMDeleteMessageReq *req = [AliVCIMDeleteMessageReq new];
req.groupId = @"xxx";        // The group ID.
req.messageId = @"yyy"; // The message ID.
NSLog(@"API - deleteMessage req: %@", req);
[[[AliVCIMEngine sharedEngine] getMessageManager] deleteMessage:req completed:^(NSError * _Nullable error) {
    NSLog(@"API - deleteMessage result: %@", error ? error.description : @"success");
}];

List recent group messages

AliVCIMListRecentMessageReq *req = [AliVCIMListRecentMessageReq new];
req.groupId = @"xxx";  // The group ID.
[[[AliVCIMEngine sharedEngine] getMessageManager] listRecentMessage:req completed:^(AliVCIMListRecentMessageRsp * _Nullable rsp, NSError * _Nullable error) {
    if (rsp) {
        // Success.
        NSLog(@"API - listRecentMessage rsp: %@", rsp);
    }
}];

List all group messages

Only the group owner or an admin can call this method.

AliVCIMListMessageReq *req = [AliVCIMListMessageReq new];
req.groupId = @"xxx";        // The group ID.
req.nextPageToken = @"xxx";  // If not provided, it indicates the first page. The server returns the next page token for traversal, which the client should include when fetching the next page.
req.type = 99999;            // Custom message type. Must be greater than 10000.
req.sortType = AliVCIMSortType_ASC;
req.pageSize = 20;
[[[AliVCIMEngine sharedEngine] getMessageManager] listMessage:req completed:^(AliVCIMListMessageRsp * _Nullable rsp, NSError * _Nullable error) {
    if (rsp) {
        // Success.
        NSLog(@"API - listMessage rsp: %@", rsp);
    }
}];

Query message history

AliVCIMListHistoryMessageReq *req = [[AliVCIMListHistoryMessageReq alloc] init];
req.groupId = @"xxx";  // The group ID.
req.nextPageToken = @"xxx";  // If not provided, it indicates the first page. The server returns the next page token for traversal, which the client should include when fetching the next page.
req.type = 99999;            // Custom message type. Must be greater than 10000.
req.sortType = AliVCIMSortType_ASC;
req.pageSize = 20;
req.beginTime = 0; // The start of the time range for traversal, in seconds. A value of 0 indicates the earliest time.
req.endTime = 0;   // The end of the time range for traversal, in seconds. A value of 0 indicates the latest time.
NSLog(@"API - listHistoryMessage req: %@", req);
[[[AliVCIMEngine sharedEngine] getMessageManager] listHistoryMessage:req completed:^(AliVCIMListHistoryMessageRsp * _Nullable rsp, NSError * _Nullable error) {
    NSLog(@"API - listHistoryMessage result: %@", error ? error.description : @"success");
    if (rsp) {
        NSLog(@"API - listHistoryMessage rsp: %@", rsp);
    }
}];

Logout

[[AliVCIMEngine sharedEngine] logout:^(NSError * _Nullable error) {
    NSLog(@"API - logout result: %@", error ? error.description : @"success");
}];

Deinitialization

After logging out, deinitialize the SDK if you no longer need it. This releases the underlying resources.

int ret = [[AliVCIMEngine sharedEngine] destroy];
NSLog(@"API - destroy result: %d", ret);

Helper APIs

Use these helper APIs to check SDK state before performing operations.

// Check if the SDK has been initialized. Your application can use this to determine if the SDK has been instantiated.
[[AliVCIMEngine sharedEngine] isInited];

// Check if the user is currently logged in. Returns false if the login process is ongoing. Post-login operations, such as joining a group or logging out, can only be performed in the logged-in state.
[[AliVCIMEngine sharedEngine] isLogin];

// Check if the user is currently logged out. Returns false if the login process is ongoing. You can only perform a login operation in the logged-out state.
[[AliVCIMEngine sharedEngine] isLogout];