> ## Documentation Index
> Fetch the complete documentation index at: https://cometchat-22654f5b-docs-ios-ui-kit-sdk-fixes.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Add Members To A Group

> Guide to adding members to groups using the CometChat iOS SDK addMembersToGroup method with scope assignment.

<Info>
  **Quick Reference for AI Agents & Developers**

  * **Add members:** `CometChat.addMembersToGroup(guid:groupMembers:bannedMembers:onSuccess:onError:)`
  * **GroupMember:** `GroupMember(UID:groupMemberScope:)` — scope: `.admin`, `.moderator`, `.participant`
  * **Permission:** Only group owner or admin can add members
  * **Related:** [Retrieve Group Members](/sdk/ios/retrieve-group-members) · [Kick Member](/sdk/ios/group-kick-member) · [Groups Overview](/sdk/ios/groups-overview)
</Info>

You can add members to the group using the `addMembersToGroup()` method. This method takes the below parameters:

1. GUID - GUID of the group the members are to be added to.
2. `Array<GroupMember>` members - This is a list of `GroupMember` objects. In order to add members, you need to create an object of the `GroupMember` class. The UID and the scope of the GroupMember are mandatory.
3. `Array<String>` bannedMembers - This is the list of UIDs that need to be banned from the Group. This can be set to `nil` if there are no members to be banned.
4. Callback.

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    let grpmem1 = GroupMember(UID: "member1", groupMemberScope: .participant)
    let grpmem2 = GroupMember(UID: "member2", groupMemberScope: .participant)
    let grpmem3 = GroupMember(UID: "member3", groupMemberScope: .admin)
    let grpmem4 = GroupMember(UID: "member4", groupMemberScope: .admin)
    let grpmem5 = GroupMember(UID: "member5", groupMemberScope: .moderator)

    CometChat.addMembersToGroup(guid: "mygroup", groupMembers: [grpmem1, grpmem2, grpmem3, grpmem4, grpmem5], onSuccess: { (response) in

    		print("Response from addMembersGroup: \\(response)")

    }, onError : { (error) in

    		print("Adding member in a group failed with error: \\(String(describing: error?.errorDescription))")

    })
    ```
  </Tab>

  <Tab title="Objective C">
    ```objc theme={null}
    GroupMember *grpmem1 = [GroupMember alloc] initWithUID: @"mem1" groupMemberScope: GroupMemberScopeTypeParticipant];
    GroupMember *grpmem2 = [GroupMember alloc] initWithUID: @"mem2" groupMemberScope: GroupMemberScopeTypeParticipant];
    GroupMember *grpmem3 = [GroupMember alloc] initWithUID: @"mem3" groupMemberScope: GroupMemberScopeTypeModerator];
    GroupMember *grpmem4 = [GroupMember alloc] initWithUID: @"mem4" groupMemberScope: GroupMemberScopeTypeModerator];
    GroupMember *grpmem5 = [GroupMember alloc] initWithUID: @"mem5" groupMemberScope: GroupMemberScopeTypeAdmin];

    NSMutableArray<GroupMember *> members = [[NSMutableArray alloc]initWithObjects:mem1, mem2, mem3, mem4, mem5, nil];
        [CometChat addMembersToGroupWithGuid:@"mygroup" groupMembers:members bannedUIDs:nil onSuccess:^(NSDictionary<NSString *,id> * _Nonnull) {

            NSLog(@"AddMembersToGroup response is successfully.");

        } onError:^(CometChatException * _Nullable)error {

            NSLog(@"AddMembersToGroup is failed with an error %@", [error.errorDescription]);
        }]
    ```
  </Tab>
</Tabs>

In the `onSuccess()` callback, you will receive a dictionary which will contain the UID of the users and the value will either be `success` or an error message describing why the operation to add the user to the group or ban the user failed.

<Accordion title="Sample Payload - addMembersToGroup() Request">
  **Method Signature:**

  | Parameter     | Type                                             | Description                                            |
  | ------------- | ------------------------------------------------ | ------------------------------------------------------ |
  | guid          | String                                           | Unique group identifier. Example: `"cometchat-guid-1"` |
  | groupMembers  | \[[GroupMember](#groupmember-object-properties)] | Array of members to add with their scopes              |
  | bannedMembers | \[String]?                                       | Array of UIDs to ban (optional). Example: `nil`        |
  | onSuccess     | (\[String: Any]) -> Void                         | Success callback with results dictionary               |
  | onError       | (CometChatException?) -> Void                    | Error callback with exception details                  |

  **Request Parameters:**

  | Parameter | Type                                             | Description                                       |
  | --------- | ------------------------------------------------ | ------------------------------------------------- |
  | guid      | String                                           | Unique group identifier. Example: `"bhut_5efde3"` |
  | members   | \[[GroupMember](#groupmember-object-properties)] | Array of GroupMember objects to add               |

  **Members Array (GroupMember Objects):**

  | Parameter | Type                             | Description                                                         |
  | --------- | -------------------------------- | ------------------------------------------------------------------- |
  | uid       | String                           | Unique identifier of the user to add. Example: `"123abc"`           |
  | scope     | [MemberScope](#memberscope-enum) | Scope to assign to the member. Example: `.participant` (value: `2`) |

  **MemberScope Enum Values:**

  | Value        | Raw Value | Description                              |
  | ------------ | --------- | ---------------------------------------- |
  | .admin       | 0         | Full group management privileges         |
  | .moderator   | 1         | Can kick/ban members, delete messages    |
  | .participant | 2         | Default scope, can send/receive messages |

  **Prerequisites:**

  | Requirement            | Description                                        |
  | ---------------------- | -------------------------------------------------- |
  | User logged in         | User must be authenticated via `CometChat.login()` |
  | Admin/Owner permission | User must be the owner or admin of the group       |
  | Valid GUID             | Group with specified GUID must exist               |
  | Valid UIDs             | Users with specified UIDs must exist               |
</Accordion>

<Accordion title="Sample Payload - addMembersToGroup() Success Response">
  **Success Callback Parameter:**

  | Parameter | Type           | Description                                    |
  | --------- | -------------- | ---------------------------------------------- |
  | response  | \[String: Any] | Dictionary with UID as key and result as value |

  **Response Dictionary Structure:**

  | Key   | Value Type | Description                                        |
  | ----- | ---------- | -------------------------------------------------- |
  | {uid} | String     | Result for each user: `"success"` or error message |

  **Example Success Response:**

  | UID    | Result  | Description                   |
  | ------ | ------- | ----------------------------- |
  | 123abc | success | Member was added successfully |

  **Possible Result Values:**

  | Value                | Description                            |
  | -------------------- | -------------------------------------- |
  | success              | Member was added successfully          |
  | ERR\_ALREADY\_JOINED | User is already a member of the group  |
  | ERR\_UID\_NOT\_FOUND | User with specified UID does not exist |
  | ERR\_USER\_BANNED    | User is banned from the group          |

  **Real-time Event Triggered:**

  | Event                | Delegate Method          | Description                                |
  | -------------------- | ------------------------ | ------------------------------------------ |
  | onMemberAddedToGroup | `CometChatGroupDelegate` | Notifies all group members of the addition |
</Accordion>

<Accordion title="Sample Payload - addMembersToGroup() Error Response">
  **Error Callback Parameter:**

  | Parameter | Type                | Description                             |
  | --------- | ------------------- | --------------------------------------- |
  | error     | CometChatException? | Error object containing failure details |

  **CometChatException Object:**

  | Parameter        | Type   | Description                                                                                         |
  | ---------------- | ------ | --------------------------------------------------------------------------------------------------- |
  | errorCode        | String | Machine-readable error code. Example: `"ERR_PERMISSION_DENIED"`                                     |
  | errorDescription | String | Human-readable error message. Example: `"You do not have permission to add members to this group."` |

  **Common Error Codes:**

  | Error Code               | Description                  | Resolution                                    |
  | ------------------------ | ---------------------------- | --------------------------------------------- |
  | ERR\_NOT\_LOGGED\_IN     | User is not logged in        | Login first using `CometChat.login()`         |
  | ERR\_GROUP\_NOT\_FOUND   | Group does not exist         | Verify the GUID is correct                    |
  | ERR\_PERMISSION\_DENIED  | No permission to add members | Only owner or admin can add members           |
  | ERR\_EMPTY\_MEMBER\_LIST | No members provided          | Provide at least one GroupMember              |
  | ERR\_INVALID\_SCOPE      | Invalid member scope         | Use `.admin`, `.moderator`, or `.participant` |
</Accordion>

## Real-Time Group Member Added Events

To receive Real-Time Events for the same, you need to implement the `onMemberAddedToGroup()` method of the `GroupListener` class.

<Note>
  When a group member is added by another member, this event is triggered. When a user joins a group on their own, the joined event is triggered.
</Note>

* `onMemberAddedToGroup()` - This method is triggered when other users are added to the group so that the logged in user is informed of the other members added to the group or this method is triggered when the LoggedIn User is added to the Group.

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    extension AppDelegate: CometChatGroupDelegate {

      func onMemberAddedToGroup(action: ActionMessage, addedBy: User, addedUser: User, addedTo: Group) {
          //When any member is added in the group this function will be called
      }

    }
    ```
  </Tab>

  <Tab title="Objective C">
    ```objc theme={null}
    @interface ViewController ()<CometChatGroupDelegate>

    @end

    @implementation ViewController

    - (void)viewDidLoad {
        [super viewDidLoad];

        [CometChat setGroupdelegate:self];
    }

    - (void)onMemberAddedToGroup:(Action *)action addedBy:(User * _Nonnull)addedBy addedUser:(User * _Nonnull)addedUser addedTo:(Group * _Nonnull)addedTo {
        //When any member is added in the group this function will be called
    }

    @end
    ```
  </Tab>
</Tabs>

<Accordion title="Sample Payload - onMemberAddedToGroup Event">
  **Event Trigger:** Received via `CometChatGroupDelegate.onMemberAddedToGroup(action:addedBy:addedUser:addedTo:)`

  **ActionMessage Object:**

  | Parameter | Type                                               | Description                     |
  | --------- | -------------------------------------------------- | ------------------------------- |
  | action    | String                                             | Action type. Example: `"added"` |
  | actionBy  | [User](/sdk/ios/users-overview#user-properties)    | User who added the member       |
  | actionOn  | [User](/sdk/ios/users-overview#user-properties)    | User who was added              |
  | actionFor | [Group](/sdk/ios/retrieve-groups#group-properties) | Group where action occurred     |

  **addedBy ([User](/sdk/ios/users-overview#user-properties) Object):**

  | Parameter | Type                                                  | Description                                                                 |
  | --------- | ----------------------------------------------------- | --------------------------------------------------------------------------- |
  | uid       | String?                                               | Unique identifier of the admin/owner. Example: `"cometchat-uid-1"`          |
  | name      | String?                                               | Display name of the admin/owner. Example: `"Admin User"`                    |
  | avatar    | String?                                               | URL to the user's avatar image. Example: `"https://example.com/avatar.png"` |
  | status    | [UserStatus](/sdk/ios/retrieve-users#userstatus-enum) | Current online status. Example: `.online`                                   |

  **addedUser ([User](/sdk/ios/users-overview#user-properties) Object):**

  | Parameter | Type                                                  | Description                                                                 |
  | --------- | ----------------------------------------------------- | --------------------------------------------------------------------------- |
  | uid       | String?                                               | Unique identifier of the added user. Example: `"cometchat-uid-2"`           |
  | name      | String?                                               | Display name of the added user. Example: `"John Doe"`                       |
  | avatar    | String?                                               | URL to the user's avatar image. Example: `"https://example.com/avatar.png"` |
  | status    | [UserStatus](/sdk/ios/retrieve-users#userstatus-enum) | Current online status. Example: `.offline`                                  |

  **addedTo ([Group](/sdk/ios/retrieve-groups#group-properties) Object):**

  | Parameter    | Type    | Description                                            |
  | ------------ | ------- | ------------------------------------------------------ |
  | guid         | String  | Unique group identifier. Example: `"cometchat-guid-1"` |
  | name         | String? | Group display name. Example: `"My Group"`              |
  | membersCount | Int     | Updated member count (incremented). Example: `6`       |
</Accordion>

## Member Added to Group event in Message History

*In other words, as a member of a group, how do I know when someone is added to the group when my app is not running?*

When you retrieve the list of previous messages if a member has been added to any group that the logged-in user is a member of, the list of messages will contain an `Action` message. An `Action` message is a sub-class of `BaseMessage` class.

For the group member added event, in the `Action` object received, the following fields can help you get the relevant information-

1. `action` - `added`
2. `actionOn` - User object containing the details of the user who was added to the group.
3. `actionBy` - User object containing the details of the user who added the member to the group.
4. `actionFor` - Group object containing the details of the group to which the member was added.

***

## Success & Failure Responses

### Add Members Success Response

When members are successfully added, the `onSuccess` callback returns a dictionary with results for each user:

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    CometChat.addMembersToGroup(guid: "mygroup", groupMembers: [grpmem1, grpmem2], onSuccess: { (response) in
        // response: [String: Any] - Dictionary with UID as key and result as value
        print("Response: \(response)")
        
        // Example response:
        // ["member1": "success", "member2": "success", "member3": "ERR_ALREADY_JOINED"]
        
        // Iterate through results
        for (uid, result) in response {
            if let resultString = result as? String {
                if resultString == "success" {
                    print("\(uid) added successfully")
                } else {
                    print("\(uid) failed: \(resultString)")
                }
            }
        }
    }, onError: { (error) in
        // Handle error
    })
    ```
  </Tab>
</Tabs>

### Add Members Failure Response

When the operation fails entirely, the `onError` callback returns a `CometChatException`:

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    CometChat.addMembersToGroup(guid: "mygroup", groupMembers: members, onSuccess: { (response) in
        // Success
    }, onError: { (error) in
        print("Error Code: \(error?.errorCode ?? "")")
        print("Error Description: \(error?.errorDescription ?? "")")
        
        // Handle specific errors
        switch error?.errorCode {
        case "ERR_GROUP_NOT_FOUND":
            // Group does not exist
            break
        case "ERR_PERMISSION_DENIED":
            // User is not admin/owner
            break
        case "ERR_EMPTY_MEMBER_LIST":
            // No members provided
            break
        default:
            break
        }
    })
    ```
  </Tab>
</Tabs>

### Response Dictionary Values

| Value                | Description                            |
| -------------------- | -------------------------------------- |
| `success`            | Member was added successfully          |
| `ERR_ALREADY_JOINED` | User is already a member of the group  |
| `ERR_UID_NOT_FOUND`  | User with specified UID does not exist |
| `ERR_USER_BANNED`    | User is banned from the group          |

### GroupMember Object Properties

| Property    | Type          | Description                               |
| ----------- | ------------- | ----------------------------------------- |
| `uid`       | `String`      | Unique identifier of the member           |
| `name`      | `String?`     | Display name                              |
| `avatar`    | `String?`     | Avatar URL                                |
| `scope`     | `MemberScope` | `.admin`, `.moderator`, or `.participant` |
| `joinedAt`  | `Double`      | Unix timestamp when member joined         |
| `hasJoined` | `Bool`        | Whether user has joined the group         |

### Common Error Codes

| Error Code              | Description                              | Resolution                                    |
| ----------------------- | ---------------------------------------- | --------------------------------------------- |
| `ERR_GROUP_NOT_FOUND`   | Group with specified GUID does not exist | Verify the GUID is correct                    |
| `ERR_PERMISSION_DENIED` | User is not admin or owner of the group  | Only admin/owner can add members              |
| `ERR_EMPTY_MEMBER_LIST` | No members provided in the array         | Provide at least one GroupMember              |
| `ERR_INVALID_SCOPE`     | Invalid member scope provided            | Use `.admin`, `.moderator`, or `.participant` |
