> ## Documentation Index
> Fetch the complete documentation index at: https://www.cometchat.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Methods

> Reference for CometChatSession, the CometChat iOS UI Kit v6's entry point: initialise, log in and out, send messages through the Kit, read feature switches and route the Kit's logs.

> [accordion] AI Integration Quick Reference
>
> ```json theme={null}
> {
>   "type": "CometChatSession (enum, CometChatCore — re-exported by CometChatSwiftUI and CometChatUIKit)",
>   "methods": {
>     "initialize(appID:region:subscribePresenceForAllUsers:overrideAdminHost:overrideClientHost:)": "async throws",
>     "initialize(appID:region:subscribePresenceForAllUsers:overrideAdminHost:overrideClientHost:enableCalling:)": "async throws — turns calling on",
>     "login(uid:authKey:)": "async throws -> User — development only",
>     "login(authToken:)": "async throws -> User — production",
>     "logout()": "async throws",
>     "loggedInUser": "User?",
>     "sendTextMessage(_:) / sendMediaMessage(_:) / sendCustomMessage(_:)": "async throws -> the server's message; announced on CometChatEvents",
>     "isPinMessageEnabled() / isSaveMessageEnabled() / isThreadSubscriptionEnabled()": "Bool"
>   },
>   "uikit extras": "CometChatUIKit.sendTextMessage(message:completion:) and its media and custom siblings",
>   "logging": "CometChatLog.sink, CometChatLog.minimumLevel, CometChatOSLogSink"
> }
> ```

`CometChatSession` is the Kit's front door: an `async` wrapper over the Chat SDK's set-up calls
with the Kit's defaults built in. Every call is `@MainActor`.

## When to use this

* Initialise the Kit once at launch, then log a user in.
* Send a message from your own code and have the Kit's lists show it.
* Check whether a server-side feature is on before showing your own UI for it.

## Prerequisites

* The `CometChatSwiftUI` or `CometChatUIKit` product added from
  `https://github.com/cometchat/cometchat-uikit-ios.git`, from `6.0.0-beta.1` — see
  [Getting Started](https://www.cometchat.com/docs/ui-kit/ios/v6/overview.md).
* Your **App ID**, **Region** and, for development, **Auth Key** from the CometChat dashboard.

`CometChatSession` lives in `CometChatCore`, which both toolkits re-export: `import CometChatSwiftUI`
or `import CometChatUIKit` is enough.

## API reference

### Initialization

#### Initialize

Call it once, before any other Kit call — at launch, before the first screen that shows chat.

> [tab] SwiftUI
>
> ```swift ChatApp.swift theme={null}
> import SwiftUI
> import CometChatSwiftUI
>
> struct RootView: View {
>     @State private var ready = false
>
>     var body: some View {
>         Group {
>             if ready { CometChatConversations() } else { ProgressView() }
>         }
>         .task {
>             do {
>                 try await CometChatSession.initialize(appID: "APP_ID", region: "REGION")
>                 if CometChatSession.loggedInUser == nil {
>                     try await CometChatSession.login(uid: "UID", authKey: "AUTH_KEY")
>                 }
>                 ready = true
>             } catch {
>                 print("set-up failed:", error.localizedDescription)
>             }
>         }
>     }
> }
> ```

> [tab] UIKit
>
> ```swift SceneDelegate.swift theme={null}
> import UIKit
> import CometChatUIKit
>
> final class SceneDelegate: UIResponder, UIWindowSceneDelegate {
>     var window: UIWindow?
>
>     func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options: UIScene.ConnectionOptions) {
>         guard let scene = scene as? UIWindowScene else { return }
>         let window = UIWindow(windowScene: scene)
>         window.rootViewController = UIViewController()
>         window.makeKeyAndVisible()
>         self.window = window
>
>         Task { @MainActor in
>             do {
>                 try await CometChatSession.initialize(appID: "APP_ID", region: "REGION")
>                 if CometChatSession.loggedInUser == nil {
>                     try await CometChatSession.login(uid: "UID", authKey: "AUTH_KEY")
>                 }
>                 window.rootViewController = UINavigationController(rootViewController: CometChatConversations())
>             } catch {
>                 print("set-up failed:", error.localizedDescription)
>             }
>         }
>     }
> }
> ```

| Parameter | Type | Default | Description |
| - | - | - | - |
| `appID` | `String` | — | Your app's id from the dashboard. Not a secret. |
| `region` | `String` | — | The region the app was created in — `"us"`, `"eu"`, `"in"`. A mismatch fails at **login**, not here. |
| `subscribePresenceForAllUsers` | `Bool` | `true` | Presence for every user, which the lists' online dots need. |
| `overrideAdminHost`, `overrideClientHost` | `String?` | `nil` | Hosts for an app outside the default environment, such as staging. |
| `enableCalling` | `Bool` | — | The overload with this parameter turns calling on; it also needs the Calls SDK linked. |

`initialize` also turns the SDK's socket on, so real-time updates arrive. There is no auth key, AI-feature list, extension list or date-formatter setting
at initialisation: the auth key goes to `login`, and date formats are set per component.

> [!NOTE]
>
> The overload `initialize(appID:region:subscribePresenceForAllUsers:enableThreadSubscription:)`
> is deprecated. Thread subscription is on by default, so `true` does nothing; `false` is the
> only app-wide opt-out. Prefer hiding the surfaces per screen.

#### Calling

```swift theme={null}
try await CometChatSession.initialize(appID: "APP_ID", region: "REGION", enableCalling: true)
print(CallingAvailability.isCallingEnabled)   // true when the Calls SDK is linked too
```

The Calls SDK is set up after the Chat SDK; if it fails, calling stays off and `initialize`
still succeeds. See [Calling Integration](https://www.cometchat.com/docs/ui-kit/ios/v6/calling-integration.md).

### Authentication

Check `loggedInUser` first: the SDK keeps the session across launches, and logging in again is
wasted work.

#### Login using Auth Key

```swift theme={null}
if CometChatSession.loggedInUser == nil {
    let user = try await CometChatSession.login(uid: "UID", authKey: "AUTH_KEY")
    print("logged in as", user.uid ?? "")
}
```

> [!WARNING]
>
> The auth key is a shared secret: anyone who unpacks your app can log in as any user. Use it
> for development only.

#### Login using Auth Token

Production apps create a user's auth token on their server and log in with it:

```swift theme={null}
let user = try await CometChatSession.login(authToken: "AUTH_TOKEN")
print("logged in as", user.uid ?? "")
```

Both logins connect the socket and, with calling on, log the Calls SDK in. Both throw a
`CometChatError` with the SDK's `code` and `message`.

### Logout

```swift theme={null}
try await CometChatSession.logout()
```

With calling on, push tokens are unregistered and the Calls SDK logs out first, while the
session still authenticates those requests.

### Create User

The Kit has no create-user call. Create users from your server with the
[REST API](https://api-explorer.cometchat.com), or with the SDK's `CometChat.createUser` during
development.

### Date Formatting

There is no app-wide date formatter. Each component that shows dates takes a
`CometChatDateTimeFormatter` — `dateTimeFormatter:` in SwiftUI, `dateTimeFormatter` in UIKit —
and several UIKit components also have a static default. Implement only the buckets you want;
`nil` keeps the Kit's text:

```swift theme={null}
struct ShortTimes: CometChatDateTimeFormatter {
    func today(_ date: Date) -> String? { date.formatted(date: .omitted, time: .shortened) }
    func yesterday(_ date: Date) -> String? { "Yday" }
}
```

| Bucket | When |
| - | - |
| `time` | a message's time |
| `today`, `yesterday`, `lastWeek`, `otherDays` | a date relative to now |
| `minute`, `minutes`, `hour`, `hours` | "last seen" ago |

### Base Message

Send through the Kit rather than the SDK when the Kit is on screen. The SDK does not echo your
own sends, so these announce each one — `messageSent` with `.inProgress`, then `.success` with
the server's message or `.error` with yours — and the message list and Conversations update.

#### Text Message

> [tab] SwiftUI
>
> ```swift theme={null}
> let message = TextMessage(receiverUid: "UID", text: "Hello", receiverType: .user)
> let sent = try await CometChatSession.sendTextMessage(message)
> print(sent.id)
> ```

> [tab] UIKit
>
> ```swift theme={null}
> let message = TextMessage(receiverUid: "UID", text: "Hello", receiverType: .user)
> // The completion is optional.
> CometChatUIKit.sendTextMessage(message: message) { result in
>     switch result {
>     case .success(let sent): print(sent.id)
>     case .failure(let error): print(error.message)
>     }
> }
> ```

#### Media Message

> [tab] SwiftUI
>
> ```swift theme={null}
> let file = URL(fileURLWithPath: "/path/to/photo.jpg")
> let message = MediaMessage(receiverUid: "UID", fileurl: file.absoluteString, messageType: .image, receiverType: .user)
> try await CometChatSession.sendMediaMessage(message)
> ```

> [tab] UIKit
>
> ```swift theme={null}
> let file = URL(fileURLWithPath: "/path/to/photo.jpg")
> let message = MediaMessage(receiverUid: "UID", fileurl: file.absoluteString, messageType: .image, receiverType: .user)
> CometChatUIKit.sendMediaMessage(message: message)
> ```

#### Custom Message

A custom message is sent with its push notification turned on.

> [tab] SwiftUI
>
> ```swift theme={null}
> let message = CustomMessage(receiverUid: "UID", receiverType: .user, customData: ["latitude": 51.5, "longitude": -0.12], type: "location")
> try await CometChatSession.sendCustomMessage(message)
> ```

> [tab] UIKit
>
> ```swift theme={null}
> let message = CustomMessage(receiverUid: "UID", receiverType: .user, customData: ["latitude": 51.5, "longitude": -0.12], type: "location")
> CometChatUIKit.sendCustomMessage(message: message)
> ```

The sender, the local id (`muid`) and the sent time are filled in when missing. On failure the
message's metadata holds the error under `error`, `errorCode` and `errorDetails`, and the call
throws (or completes with `.failure`).

### Feature Flags

Read the server-side switches the Kit's own options are gated on:

```swift theme={null}
let canPin = CometChatSession.isPinMessageEnabled()       // false until app settings are fetched
let canSave = CometChatSession.isSaveMessageEnabled()
let threads = CometChatSession.isThreadSubscriptionEnabled()
print(canPin, canSave, threads)
```

### Logging

The Kit is silent by default. Give it a sink to see what it does — sessions, listeners, pages,
error codes. Events never carry message text, names, tokens or credentials, and ids are hashed.

```swift theme={null}
CometChatLog.sink = CometChatOSLogSink()   // the system log, subsystem "com.cometchat.uikit"
CometChatLog.minimumLevel = .debug          // .debug, .info (default), .warning, .error
```

Implement `CometChatLogSink` to send them to your own diagnostics; `receive(_:)` can be called
from any thread.

## Next steps

> [card] [Getting Started](https://www.cometchat.com/docs/ui-kit/ios/v6/overview.md)
>
> Install and set up the Kit

> [card] [Events](https://www.cometchat.com/docs/ui-kit/ios/v6/events.md)
>
> What the Kit announces, and what you must

> [card] [Architecture](https://www.cometchat.com/docs/ui-kit/ios/v6/architecture-data-flow.md)
>
> How the products are layered

> [card] [Troubleshooting](https://www.cometchat.com/docs/ui-kit/ios/v6/troubleshooting.md)
>
> Common problems and fixes


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.