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

# iOS SDK Reference

> Browse the iOS AvatarKit SDK API reference.

## Installation

Download the latest [AvatarKit.xcframework](https://github.com/spatius-ai/avatarkit-ios-release/releases/latest) from the releases page, unzip, and drag it into your Xcode project. Set **Embed & Sign** in your target's **Frameworks, Libraries, and Embedded Content**.

### AvatarSDK

Main initialization and configuration interface for AvatarKit.

```swift theme={null}
@MainActor enum AvatarSDK
```

##### Type Properties

<Accordion title="appID">
  The app identifier.

  ```swift theme={null}
  static var appID: String { get }
  ```
</Accordion>

<Accordion title="configuration">
  The app configuration.

  ```swift theme={null}
  static var configuration: Configuration { get }
  ```
</Accordion>

<Accordion title="sessionToken">
  The session token used to authenticate avatars with Motion Server.

  ```swift theme={null}
  static var sessionToken: String
  ```
</Accordion>

<Accordion title="userID">
  The user identifier provided by the developer to identify the user in the AvatarKit Log Service.

  ```swift theme={null}
  static var userID: String
  ```
</Accordion>

<Accordion title="version">
  Returns the version of AvatarKit.

  ```swift theme={null}
  static var version: String { get }
  ```
</Accordion>

##### Type Methods

<Accordion title="initialize(appID:configuration:)">
  Initialize AvatarKit.

  ```swift theme={null}
  static func initialize(appID: String, configuration: Configuration)
  ```

  **Parameters:**

  * `appID`: The app identifier
  * `configuration`: The configuration for AvatarKit
</Accordion>

<Accordion title="setRenderQuality(_:)">
  Update the global rendering quality tier.

  ```swift theme={null}
  static func setRenderQuality(_ quality: RenderQuality)
  ```
</Accordion>

<Accordion title="setRenderResolutionCap(enabled:maxHeight:)">
  Cap render backing-buffer height while preserving the view's CSS/layout size.

  ```swift theme={null}
  static func setRenderResolutionCap(enabled: Bool, maxHeight: Int = 1440)
  ```
</Accordion>

<Accordion title="isDeviceSupported()">
  Check whether the current device can run AvatarKit.

  ```swift theme={null}
  static func isDeviceSupported() async -> Bool
  ```
</Accordion>

<Accordion title="deviceScore()">
  Measures the device's computational performance for avatar rendering.

  ```swift theme={null}
  static func deviceScore() async -> AvatarSDK.DeviceScore
  ```
</Accordion>

### AvatarManager

Manage avatar asset loading, caching, and retrieval.

```swift theme={null}
final class AvatarManager
```

##### Type Properties

<Accordion title="shared">
  The shared avatar manager instance.

  ```swift theme={null}
  static let shared: AvatarManager
  ```
</Accordion>

##### Instance Methods

<Accordion title="load(id:onProgress:)">
  Loads an avatar by ID.

  ```swift theme={null}
  func load(id: String, onProgress: (ProgressHandler)?) async throws -> Avatar
  ```

  **Parameters:**

  * `id`: The avatar identifier
  * `onProgress`: Optional progress callback

  **Returns:** The loaded `Avatar` instance.
</Accordion>

<Accordion title="cancelLoading(id:)">
  Cancels the loading of avatar by ID.

  ```swift theme={null}
  func cancelLoading(id: String) async
  ```

  **Parameters:**

  * `id`: The avatar identifier
</Accordion>

<Accordion title="cancelAllLoading()">
  Cancels all loading of avatars.

  ```swift theme={null}
  func cancelAllLoading() async
  ```
</Accordion>

<Accordion title="retrieve(id:)">
  Retrieves a cached avatar by ID.

  ```swift theme={null}
  func retrieve(id: String) -> Avatar?
  ```

  **Parameters:**

  * `id`: The avatar identifier

  **Returns:** The cached `Avatar` if available, otherwise `nil`.
</Accordion>

<Accordion title="derive(assetPath:)">
  Derives an avatar from a local asset path.

  ```swift theme={null}
  func derive(assetPath: String) throws -> Avatar
  ```

  **Parameters:**

  * `assetPath`: The path to the avatar asset

  **Returns:** The derived `Avatar` instance.
</Accordion>

<Accordion title="clear(id:)">
  Clears cached data for a specific avatar.

  ```swift theme={null}
  func clear(id: String) throws
  ```

  **Parameters:**

  * `id`: The avatar identifier to clear
</Accordion>

<Accordion title="clearAll()">
  Clears all cached avatar data.

  ```swift theme={null}
  func clearAll() throws
  ```
</Accordion>

<Accordion title="clearLRU(keepCount:)">
  Clears least recently used avatars, keeping the specified count.

  ```swift theme={null}
  func clearLRU(keepCount: Int) throws
  ```

  **Parameters:**

  * `keepCount`: Number of most recently used avatars to keep
</Accordion>

<Accordion title="getCacheSize(id:)">
  Gets the cache size for a specific avatar.

  ```swift theme={null}
  func getCacheSize(id: String) throws -> Int
  ```

  **Parameters:**

  * `id`: The avatar identifier

  **Returns:** The cache size in bytes.
</Accordion>

<Accordion title="getAllCacheSize()">
  Gets the total cache size for all avatars.

  ```swift theme={null}
  func getAllCacheSize() throws -> Int
  ```

  **Returns:** The total cache size in bytes.
</Accordion>

### AvatarController

The main controller for managing avatar driving service connections and interactions.

```swift theme={null}
@MainActor final class AvatarController
```

##### Instance Properties

<Accordion title="onFirstRendering">
  Callback when the avatar is first rendered.

  ```swift theme={null}
  var onFirstRendering: (() -> Void)?
  ```
</Accordion>

<Accordion title="onConnectionState">
  Callback for connection state changes.

  ```swift theme={null}
  var onConnectionState: ((ConnectionState) -> Void)?
  ```
</Accordion>

<Accordion title="onConversationState">
  Callback for conversation state changes.

  ```swift theme={null}
  var onConversationState: ((ConversationState) -> Void)?
  ```
</Accordion>

<Accordion title="onError">
  Callback for error events.

  ```swift theme={null}
  var onError: ((AvatarError) -> Void)?
  ```
</Accordion>

<Accordion title="start()">
  Starts the avatar driving service connection.

  ```swift theme={null}
  func start()
  ```
</Accordion>

<Accordion title="close()">
  Closes the avatar driving service.

  ```swift theme={null}
  func close()
  ```
</Accordion>

<Accordion title="pauseRendering()">
  Pauses avatar rendering.

  ```swift theme={null}
  func pauseRendering()
  ```
</Accordion>

<Accordion title="resumeRendering()">
  Resumes avatar rendering.

  ```swift theme={null}
  func resumeRendering()
  ```
</Accordion>

<Accordion title="isRendering">
  Whether the current avatar is actually rendering.

  ```swift theme={null}
  var isRendering: Bool { get }
  ```
</Accordion>

<Accordion title="interrupt()">
  Stops playback and terminates the current conversation.

  ```swift theme={null}
  func interrupt()
  ```
</Accordion>

<Accordion title="send(_:end:)">
  Sends audio to the avatar driving service.

  For audio source and timing guidance, see [Audio](/concepts/audio).

  ```swift theme={null}
  func send(_ data: Data, end: Bool) -> String
  ```

  **Parameters:**

  * `data`: The audio data to send
  * `end`: Whether this is the end of the audio stream

  **Returns:** A conversation ID string.
</Accordion>

<Accordion title="yield(_:end:audioFormat:)">
  Yields audio from the host.

  ```swift theme={null}
  func yield(_ data: Data, end: Bool, audioFormat: AudioFormat?) -> String
  ```

  **Parameters:**

  * `data`: The audio data
  * `end`: Whether this is the end of the audio stream
  * `audioFormat`: The audio format (optional)

  **Returns:** A conversation ID string.
</Accordion>

<Accordion title="yield(_:conversationID:)">
  Yields animations from the host.

  ```swift theme={null}
  func yield(_ animations: [Data], conversationID: String)
  ```

  **Parameters:**

  * `animations`: Array of encoded motion data frames
  * `conversationID`: The conversation identifier
</Accordion>

<Accordion title="pointCount">
  The point count of the current avatar.

  ```swift theme={null}
  var pointCount: Int { get }
  ```
</Accordion>

<Accordion title="volume">
  The volume of playback.

  ```swift theme={null}
  var volume: Float
  ```
</Accordion>

### AvatarView

A UIView subclass for rendering avatars.

```swift theme={null}
@MainActor final class AvatarView: UIView
```

##### Initializers

<Accordion title="init(avatar:)">
  Creates a new avatar view with the specified avatar.

  ```swift theme={null}
  init(avatar: Avatar)
  ```

  **Parameters:**

  * `avatar`: The avatar to display
</Accordion>

##### Instance Properties

<Accordion title="controller">
  The controller for the avatar.

  ```swift theme={null}
  var controller: AvatarController { get }
  ```
</Accordion>

<Accordion title="contentTransform">
  Transform for avatar content position and scale within the view.

  ```swift theme={null}
  var contentTransform: Transform
  ```
</Accordion>

#### Render over an Avatar Background

Download the optional 16:9 background from Spatius Studio and add it to the Asset Catalog. Place the image and `AvatarView` in the same `ZStack`, with the image first. `AvatarView` is transparent by default, so the background shows through.

```swift theme={null}
struct AvatarLayer: UIViewRepresentable {
    let avatar: Avatar

    func makeUIView(context: Context) -> AvatarView {
        AvatarView(avatar: avatar)
    }

    func updateUIView(_ avatarView: AvatarView, context: Context) {}
}

struct AvatarStage: View {
    let avatar: Avatar

    var body: some View {
        ZStack {
            Image("AvatarBackground")
                .resizable()
                .aspectRatio(contentMode: .fill)

            AvatarLayer(avatar: avatar)
        }
        .aspectRatio(16 / 9, contentMode: .fit)
        .clipped()
    }
}
```

For square or portrait display windows, center this 16:9 stage inside a clipped outer view. See [Avatar Background](/concepts/avatar-background) for the shared cropping rules.

***

### Avatar

Represents an avatar instance.

```swift theme={null}
struct Avatar
```

| Instance Property | Type     | Description                                   |
| ----------------- | -------- | --------------------------------------------- |
| `id`              | `String` | The avatar identifier.                        |
| `isFromCache`     | `Bool`   | Whether the instance of avatar is from cache. |

### Configuration

Configuration for AvatarKit.

```swift theme={null}
struct Configuration
```

##### Initializers

<Accordion title="init(region:audioFormat:drivingServiceMode:logLevel:renderQuality:)">
  Creates a new configuration with the specified parameters.

  ```swift theme={null}
  init(
      region: String = DEFAULT_REGION,
      audioFormat: AudioFormat = .init(),
      drivingServiceMode: DrivingServiceMode = .direct,
      logLevel: LogLevel = .off,
      renderQuality: RenderQuality = .ultra
  )
  ```

  **Parameters:**

  * `region`: The region to connect to (`"us-west"`, `"ap-northeast"`, or `"cn-beijing"`)
  * `audioFormat`: The audio format configuration
  * `drivingServiceMode`: The driving service mode
  * `logLevel`: The log level
  * `renderQuality`: Render quality tier
</Accordion>

| Instance Property    | Type                 | Description                                                                        |
| -------------------- | -------------------- | ---------------------------------------------------------------------------------- |
| `region`             | `String`             | The region the SDK connects to (`"us-west"`, `"ap-northeast"`, or `"cn-beijing"`). |
| `audioFormat`        | `AudioFormat`        | Audio format for AvatarKit.                                                        |
| `drivingServiceMode` | `DrivingServiceMode` | Driving service mode for AvatarKit.                                                |
| `logLevel`           | `LogLevel`           | Log level for AvatarKit.                                                           |
| `renderQuality`      | `RenderQuality`      | Render quality tier for AvatarKit.                                                 |

### AudioFormat

Audio format configuration for AvatarKit.

```swift theme={null}
struct AudioFormat
```

##### Initializers

<Accordion title="init(sampleRate:)">
  Creates a new audio format with the specified sample rate.

  ```swift theme={null}
  init(sampleRate: Int)
  ```

  **Parameters:**

  * `sampleRate`: The audio sample rate in Hz
</Accordion>

| Instance Property | Type  | Description                                        |
| ----------------- | ----- | -------------------------------------------------- |
| `sampleRate`      | `Int` | The audio sample rate in Hz.                       |
| `channelCount`    | `Int` | The number of audio channels. Fixed to 1 for mono. |

### DrivingServiceMode

Driving service modes for AvatarKit.

```swift theme={null}
enum DrivingServiceMode
```

| Case      | Description                                                           |
| --------- | --------------------------------------------------------------------- |
| `direct`  | The SDK handles the Motion Server connection directly.                |
| `backend` | The host application provides encoded audio and motion data payloads. |

### RenderQuality

Render quality tiers for AvatarKit.

```swift theme={null}
enum RenderQuality
```

| Case       | Description                          |
| ---------- | ------------------------------------ |
| `standard` | Lower rendering cost.                |
| `high`     | Balanced quality and rendering cost. |
| `ultra`    | Highest quality. Default.            |

### FrameStarvationMode

Controls playback behavior when motion data cannot keep up with the audio clock.

```swift theme={null}
enum FrameStarvationMode
```

| Case               | Description                                                                      |
| ------------------ | -------------------------------------------------------------------------------- |
| `audioIndependent` | Audio keeps playing while motion data catches up. Default.                       |
| `strictSync`       | Audio pauses when motion data runs out and resumes when new motion data arrives. |

### LogLevel

Log levels for AvatarKit.

```swift theme={null}
enum LogLevel
```

| Case      | Description                   |
| --------- | ----------------------------- |
| `all`     | Log all messages.             |
| `warning` | Log warnings and errors only. |
| `error`   | Log errors only.              |
| `off`     | Disable logging.              |

### ConnectionState

Connection states for AvatarKit.

```swift theme={null}
enum ConnectionState
```

| Case            | Description                          |
| --------------- | ------------------------------------ |
| `connecting`    | The connection is being established. |
| `connected`     | The connection is active.            |
| `disconnected`  | The connection has been closed.      |
| `failed(Error)` | The connection failed with an error. |

### ConversationState

Conversation states for AvatarKit.

```swift theme={null}
enum ConversationState
```

| Case      | Description                            |
| --------- | -------------------------------------- |
| `idle`    | No active conversation.                |
| `playing` | The avatar is playing audio/animation. |
| `paused`  | The conversation is paused.            |

### Transform

Transform for avatar content rendering.

```swift theme={null}
struct Transform
```

##### Initializers

<Accordion title="init(x:y:scale:)">
  Creates a new transform with the specified translation and scale.

  ```swift theme={null}
  init(x: Float, y: Float, scale: Float)
  ```

  **Parameters:**

  * `x`: The x-axis translation
  * `y`: The y-axis translation
  * `scale`: The scale factor
</Accordion>

| Type Property | Type        | Description             |
| ------------- | ----------- | ----------------------- |
| `identity`    | `Transform` | The identity transform. |

| Instance Property | Type    | Description             |
| ----------------- | ------- | ----------------------- |
| `x`               | `Float` | The x-axis translation. |
| `y`               | `Float` | The y-axis translation. |
| `scale`           | `Float` | The scale factor.       |

### AvatarError

Avatar errors for AvatarKit.

```swift theme={null}
enum AvatarError: LocalizedError
```

| Case                           | Description                       |
| ------------------------------ | --------------------------------- |
| `appIDUnrecognized`            | The app ID is not recognized.     |
| `avatarIDUnrecognized`         | The avatar ID is not recognized.  |
| `avatarAssetMissing`           | The avatar asset is missing.      |
| `failedToDownloadAvatarAssets` | Failed to download avatar assets. |
| `failedToFetchAvatarMetadata`  | Failed to fetch avatar metadata.  |
| `sessionTokenExpired`          | The session token has expired.    |
| `sessionTokenInvalid`          | The session token is invalid.     |

| Instance Property  | Type      | Description                           |
| ------------------ | --------- | ------------------------------------- |
| `errorDescription` | `String?` | A localized description of the error. |
| `failureReason`    | `String?` | The reason for the failure.           |
