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

# Block Users

> Guide to blocking and unblocking users using the CometChat iOS SDK to control messaging permissions.

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

  * **Block users:** `CometChat.blockUsers(_:onSuccess:onError:)` — pass array of UIDs
  * **Unblock users:** `CometChat.unblockUsers(_:onSuccess:onError:)` — pass array of UIDs
  * **Get blocked users:** `BlockedUserRequest.BlockedUserRequestBuilder.set(limit:).build()` → `fetchNext(onSuccess:onError:)`
  * **Filter direction:** `.set(direction:)` — `.byMe`, `.me`, `.both`
  * **Related:** [Retrieve Users](/sdk/ios/retrieve-users) · [Users Overview](/sdk/ios/users-overview)
</Info>

## Block Users

*In other words, as a logged-in user, how do I block a user from sending me messages?*

You can block users using the `blockUsers()` method. Once any user is blocked, all the communication to and from the respective user will be completely blocked. You can block multiple users in a single operation. The`blockUsers()` method takes an array of string as a parameter that holds the list of UIDs to be blocked.

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    let blockUsers = ["UID1", "UID2", "UID3"]

    CometChat.blockUsers(blockUsers, onSuccess: {
                    
       print("Blocked user successfully.")
                    
    }, onError: { (error) in
                    
       print("Blocked user failed with error: \\(error?.errorDescription)")
                    
    })
    ```
  </Tab>

  <Tab title="Objective C">
    ```objc theme={null}
    NSMutableArray *users = [NSMutableArray alloc]init];
    [users addObject:@"UID1"];
    [users addObject:@"UID2"];
    [users addObject:@"UID3"];

    [CometChat blockUsers: users onSuccess:^ (NSDictionary *dict) {

      NSLog(@"Blocked user successfully.");
      
    }, onError:^ (CometChatException *error){

      NSLog(@"Blocked user failed with error: %@", error.errorDescription);
    }];
    ```
  </Tab>
</Tabs>

In the `onSuccess()` callback, you receive a dictionary which contains UIDs as the keys and "success" or "fail" as the value based on if the block operation for the UID was successful or not.

<Accordion title="Sample Payload">
  **Request Parameters:**

  | Parameter | Type      | Description                                                 |
  | --------- | --------- | ----------------------------------------------------------- |
  | UIDs      | \[String] | Array of user UIDs to block. Example: `["cometchat-uid-2"]` |

  **Success Response (Dictionary \[String: Any]):**

  | Parameter | Type | Description                                                                                               |
  | --------- | ---- | --------------------------------------------------------------------------------------------------------- |
  | {uid}     | Bool | Key is the UID, value indicates success (`true`) or failure (`false`). Example: `"cometchat-uid-2": true` |

  **Error Response ([CometChatException](#common-error-codes)):**

  | Parameter        | Type   | Description                                                                                      |
  | ---------------- | ------ | ------------------------------------------------------------------------------------------------ |
  | errorCode        | String | Unique error code identifying the error type. Example: `"ERR_UID_NOT_FOUND"`                     |
  | errorDescription | String | Human-readable description of the error. Example: `"User with the specified UID does not exist"` |
</Accordion>

## Unblock Users

You can unblock the already blocked users using the `unblockUsers()` method. You can unblock multiple users in a single operation. The`unblockUsers()` method takes an array of string as a parameter that holds the list of UIDs to be unblocked.

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    let unblockUsers = ["UID1", "UID2", "UID3"]

    CometChat.unblockUsers(unblockUsers, onSuccess: { (users) in
                    
       print("Unblocked user successfully.")
                    
    }, onError: { (error) in
                    
       print("Unblocked user failed with error: \\(error?.errorDescription)")
                    
    })
    ```
  </Tab>

  <Tab title="Objective C">
    ```objc theme={null}
    NSMutableArray *users = [NSMutableArray alloc]init];
    [users addObject:@"UID1"];
    [users addObject:@"UID2"];
    [users addObject:@"UID3"];

    [CometChat unblockUsers: users onSuccess:^ (NSDictionary *dict){

      NSLog(@"unblocked user successfully.");
      
    }, onError:^ (CometChatException *error){

      NSLog(@"unblocked user failed with error : %@", error.errorDescription);
    }];
    ```
  </Tab>
</Tabs>

In the `onSuccess()` callback, you receive a HashMap which contains UIDs as the keys and "success" or "fail" as the value based on if the unblock operation for the UID was successful or not.

<Accordion title="Sample Payload">
  **Request Parameters:**

  | Parameter | Type      | Description                                                   |
  | --------- | --------- | ------------------------------------------------------------- |
  | UIDs      | \[String] | Array of user UIDs to unblock. Example: `["cometchat-uid-2"]` |

  **Success Response (Dictionary \[String: Any]):**

  | Parameter | Type | Description                                                                                               |
  | --------- | ---- | --------------------------------------------------------------------------------------------------------- |
  | {uid}     | Bool | Key is the UID, value indicates success (`true`) or failure (`false`). Example: `"cometchat-uid-2": true` |

  **Error Response ([CometChatException](#common-error-codes)):**

  | Parameter        | Type   | Description                                                                                      |
  | ---------------- | ------ | ------------------------------------------------------------------------------------------------ |
  | errorCode        | String | Unique error code identifying the error type. Example: `"ERR_UID_NOT_FOUND"`                     |
  | errorDescription | String | Human-readable description of the error. Example: `"User with the specified UID does not exist"` |
</Accordion>

## Get list of blocked users

In order to fetch the list of blocked users, you can use the `BlockedUsersRequest` class. To use this class i.e to create an object of the `BlockedUsersRequest class`, you need to use the `BlockedUsersRequestBuilder` class. The `BlockedUsersRequestBuilder` class allows you to set the parameters based on which the blocked users are to be fetched.

### BlockedUserRequestBuilder Methods

| Method                | Type                                   | Description                                          |
| --------------------- | -------------------------------------- | ---------------------------------------------------- |
| `set(limit:)`         | Int                                    | Number of blocked users to fetch per request (1-100) |
| `set(searchKeyword:)` | String                                 | Search string to filter blocked users                |
| `set(direction:)`     | [CometChat.Blocked](#direction-values) | Filter direction: `.byMe`, `.me`, `.both`            |

<Accordion title="Sample Payload - BlockedUserRequestBuilder">
  **Builder Configuration:**

  | Parameter     | Type                                   | Description                                                                       |
  | ------------- | -------------------------------------- | --------------------------------------------------------------------------------- |
  | limit         | Int                                    | Maximum number of blocked users to fetch per request. Range: 1-100. Example: `20` |
  | searchKeyword | String                                 | Search string to filter blocked users by UID or name. Example: `"john"`           |
  | direction     | [CometChat.Blocked](#direction-values) | Filter direction for blocked users list. Example: `.byMe`                         |

  **Direction Values:**

  | Value | Description                                                         |
  | ----- | ------------------------------------------------------------------- |
  | .byMe | Returns only users blocked by the logged-in user                    |
  | .me   | Returns only users who have blocked the logged-in user              |
  | .both | Returns both users blocked by me and users who blocked me (default) |

  **Common Filter Combinations:**

  | Use Case                        | Builder Configuration                                              |
  | ------------------------------- | ------------------------------------------------------------------ |
  | Fetch users I blocked           | `.set(direction: .byMe).set(limit: 20)`                            |
  | Fetch users who blocked me      | `.set(direction: .me).set(limit: 20)`                              |
  | Fetch all blocked relationships | `.set(direction: .both).set(limit: 20)`                            |
  | Search blocked users by name    | `.set(searchKeyword: "john").set(direction: .byMe).set(limit: 20)` |
</Accordion>

The `BlockedUsersRequestBuilder` class allows you to set the below parameters:

1. `set(limit: Int)` - This method sets the limit i.e. the number of blocked users that should be fetched in a single iteration.

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    let blockedUserRequest = BlockedUserRequest.BlockedUserRequestBuilder.set(limit: 20).build();
    ```
  </Tab>
</Tabs>

2. `set(searchKeyword: String)` - This method allows you to set the search string based on which the blocked users are to be fetched.

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    let blockedUserRequest = BlockedUserRequest.BlockedUserRequestBuilder
    .set(searchKeyword: "abc")
    .set(limit: 20)
    .build();
    ```
  </Tab>
</Tabs>

3. `set(direction: CometChat.Blocked)` - This can hold one of the below values: a. CometChat.Blocked.byMe - This will ensure that the list of blocked users only contains the users blocked by the logged-in user. b. CometChat.Blocked.me - setting the direction to this will return only the list of users that have blocked the logged-in user. c. CometChat.Blocked.both - this will make sure the list of users includes both the above cases. This is the default value for the direction variable if it is not set.

### Direction Values

| Value | Description                               |
| ----- | ----------------------------------------- |
| .byMe | Users blocked by the logged-in user       |
| .me   | Users who have blocked the logged-in user |
| .both | Both of the above (default)               |

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    let blockedUserRequest = BlockedUserRequest.BlockedUserRequestBuilder
    .set(searchKeyword: "abc")
    .set(limit: 20)
    .set(direction: .both)
    .build();
    ```
  </Tab>
</Tabs>

Finally, once all the parameters are set to the builder class, you need to call the build() method to get the object of the `BlockedUsersRequest` class.

Once you have the object of the `BlockedUsersRequest` class, you need to call the `fetchNext()` method. Calling this method will return a list of `User` objects containing n number of blocked users where n is the limit set in the builder class.

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    let blockedUserRequest = BlockedUserRequest.BlockedUserRequestBuilder(limit: 20).build();

    blockedUserRequest.fetchNext(onSuccess : { (users) in
                
       print("Blocked users: \\(users)")
                
    }, onError : { (error) in
                
       print("Error while fetching the blocked user request:  \\(error?.errorDescription)")

    })
    ```
  </Tab>

  <Tab title="Objective C">
    ```objc theme={null}
    BlockedUserRequest *blockedUserRequest = [[[BlockedUserRequestBuilder alloc]initWithLimit:2] build];

    [blockedUserRequest fetchNextOnSuccess: ^(NSArray<User *> * users){

      NSLog(@"Blocked user list fetched successfully.")
      
    } onError:^ (CometChatException *error){

      NSLog(@"Fetching block user list failed with error: %@", error.errorDescription);
      
    }];
    ```
  </Tab>
</Tabs>

<Accordion title="Sample Payload">
  **Request Parameters:**

  | Parameter | Type                                   | Description                                             |
  | --------- | -------------------------------------- | ------------------------------------------------------- |
  | limit     | Int                                    | Maximum number of blocked users to fetch. Example: `30` |
  | direction | [CometChat.Blocked](#direction-values) | Filter direction for blocked users. Example: `.byMe`    |

  **Success Response - Users Blocked By Me (Array of [User](/sdk/ios/users-overview#user-properties) Objects):**

  | Parameter     | Type                                                  | Description                                                                                                      |
  | ------------- | ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
  | uid           | String?                                               | Unique identifier of the blocked user. Example: `"cometchat-uid-2"`                                              |
  | name          | String?                                               | Display name of the blocked user. Example: `"George Alan"`                                                       |
  | avatar        | String?                                               | URL to the user's avatar image. Example: `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` |
  | link          | String?                                               | URL to the user's profile page. Example: `nil`                                                                   |
  | role          | String?                                               | Role assigned to the user. Example: `"default"`                                                                  |
  | status        | [UserStatus](/sdk/ios/retrieve-users#userstatus-enum) | Current online status of the user. Example: `.offline`                                                           |
  | statusMessage | String?                                               | Custom status message set by the user. Example: `nil`                                                            |
  | lastActiveAt  | Double                                                | Unix timestamp of the user's last activity. Example: `1771571894.0`                                              |
  | hasBlockedMe  | Bool                                                  | Indicates if this user has blocked the logged-in user. Example: `false`                                          |
  | blockedByMe   | Bool                                                  | Indicates if the logged-in user has blocked this user. Example: `true`                                           |
  | deactivatedAt | Double                                                | Unix timestamp when user was deactivated (0 if active). Example: `0.0`                                           |
  | tags          | \[String]                                             | Array of tags associated with the user. Example: `[]`                                                            |
  | metadata      | \[String: Any]?                                       | Custom metadata dictionary. Example: `[:]`                                                                       |

  **Success Response - Users Who Blocked Me (Array of [User](/sdk/ios/users-overview#user-properties) Objects):**

  | Parameter     | Type                                                  | Description                                                                                                      |
  | ------------- | ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
  | uid           | String?                                               | Unique identifier of the user who blocked me. Example: `"cometchat-uid-5"`                                       |
  | name          | String?                                               | Display name of the user. Example: `"Mike Johnson"`                                                              |
  | avatar        | String?                                               | URL to the user's avatar image. Example: `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-5.webp"` |
  | link          | String?                                               | URL to the user's profile page. Example: `nil`                                                                   |
  | role          | String?                                               | Role assigned to the user. Example: `"default"`                                                                  |
  | status        | [UserStatus](/sdk/ios/retrieve-users#userstatus-enum) | Current online status of the user. Example: `.online`                                                            |
  | statusMessage | String?                                               | Custom status message set by the user. Example: `nil`                                                            |
  | lastActiveAt  | Double                                                | Unix timestamp of the user's last activity. Example: `1771572000.0`                                              |
  | hasBlockedMe  | Bool                                                  | Indicates if this user has blocked the logged-in user. Example: `true`                                           |
  | blockedByMe   | Bool                                                  | Indicates if the logged-in user has blocked this user. Example: `false`                                          |
  | deactivatedAt | Double                                                | Unix timestamp when user was deactivated (0 if active). Example: `0.0`                                           |
  | tags          | \[String]                                             | Array of tags associated with the user. Example: `[]`                                                            |
  | metadata      | \[String: Any]?                                       | Custom metadata dictionary. Example: `[:]`                                                                       |

  **Error Response ([CometChatException](#common-error-codes)):**

  | Parameter        | Type   | Description                                                                  |
  | ---------------- | ------ | ---------------------------------------------------------------------------- |
  | errorCode        | String | Unique error code identifying the error type. Example: `"ERR_NOT_LOGGED_IN"` |
  | errorDescription | String | Human-readable description of the error. Example: `"User is not logged in"`  |
</Accordion>

***

## Common Error Codes

| Error Code           | Description           | Resolution                            |
| -------------------- | --------------------- | ------------------------------------- |
| ERR\_NOT\_LOGGED\_IN | User is not logged in | Login first using `CometChat.login()` |
| ERR\_UID\_NOT\_FOUND | User UID not found    | Verify the UID is correct             |
| ERR\_INVALID\_LIMIT  | Invalid limit value   | Use a limit between 1-100             |
