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

# API 参考

> Swift SDK 暴露的全部类型与方法。

## `KontextAds.createSession(_:)`

```swift theme={null}
@MainActor
public static func createSession(_ options: SessionOptions) -> Session
```

根据传入的 `SessionOptions` 创建并返回一个新的 `Session`，并在后台触发 `/init`。

## `SessionOptions`

**publisherToken** `String` *required*

你的 publisher token。

**userId** `String` *required*

终端用户的稳定标识。用于个性化、频次封顶与奖励广告。

**conversationId** `String` *required*

当前对话 / 聊天线程的唯一 ID。

**enabledPlacementCodes** `[String]?`

本次会话请求广告的 placement code。为 nil 或空时默认 `["inlineAd"]`。

**character** `Character?`

用于上下文定向的 AI 角色元数据。

**字段**

**id** `String` *required*

**name** `String` *required*

**avatarUrl** `URL` *required*

**greeting** `String?`

**persona** `String?`

**tags** `[String]?`

**isNsfw** `Bool?`

**variantId** `String?`

发布方定义的用户分群标识（例如用于 A/B 测试）。

**regulatory** `Regulatory?`

隐私 / consent 信号。如果集成了兼容 TCF 的 CMP，TCF 字段（`gdpr` / `gdprConsent`）会被自动收集——只有 COPPA、GPP、US Privacy 才需要手动设置。

**字段**

**gdpr** `Int?`

0、1 或 nil。

**gdprConsent** `String?`

IAB TCF v2 consent 字符串。

**coppa** `Int?`

0、1 或 nil。

**gpp** `String?`

Global Privacy Platform 字符串。

**gppSid** `[Int]?`

适用的 GPP section ID。

**usPrivacy** `String?`

CCPA / LSPA 字符串。

**userEmail** `String?`

终端用户邮箱，用于频次封顶去重。

**advertisingId** `String?`

你自行收集的 IDFA。优先级高于 SDK 的自动收集。请配合 `requestTrackingAuthorization: false` 使用。

**vendorId** `String?`

你自行收集的 IDFV。为 nil 时会回退到 `UIDevice.current.identifierForVendor`。

**requestTrackingAuthorization** `Bool`

SDK 是否自动请求 ATT 授权。默认 `true`。

**onEvent** `(AdEvent) -\> Void`

每个广告生命周期事件触发时的回调，在主线程上调用。

## `Session`

**addMessage(\_:options:)** `method`

把一条 `Message` 追加进对话。同步返回。用户消息会触发一次防抖后的预加载。

```swift theme={null}
session.addMessage(Message(id: "m1", role: .user, content: "Hi"))
session.addMessage(
    Message(id: "m2", role: .user, content: "Hi"),
    options: AddMessageOptions(trackOnly: true)
)
```

当 `trackOnly: true` 时，preload 仍会发出（用于分析），但不会产生广告。

**createAd(\_:options:)** `method`

返回与给定 `messageId` 对应的 `Ad`。幂等——同一个 `messageId` + placement code 多次调用会返回同一个 `Ad`。请缓存结果。

```swift theme={null}
let ad = session.createAd("m2")
let sidebar = session.createAd("m2", options: AdOptions(code: "sidebar", theme: "dark"))
```

**updateOptions(\_:)** `method`

实时更新与预加载相关的字段。详见 [实践指南 → 会话选项的实时更新](https://docs.kontext.so/sdk/swift/guides.md#live-updating-session-options)。

**destroy()** `method`

销毁会话：取消预加载、销毁广告、释放 web view。幂等。

**eventPublisher** `AnyPublisher\<AdEvent, Never\>`

与 `onEvent` 发出相同事件的 Combine publisher。在 SwiftUI / Combine 管线中很有用。

**messages** `[Message]`

会话跟踪的消息的只读快照。

**sessionId** `UUID?`

服务端分配的 session ID。首次 preload 成功之前为 `nil`。

**disabled** `Bool`

若服务端在 `/init` 响应中永久关闭了该会话（例如地域限制），返回 `true`。后续预加载会被跳过。

**destroyed** `Bool`

`destroy()` 被调用过后返回 `true`。

## `MutablePublisherOptions`

`session.updateOptions(_:)` 接受的 `SessionOptions` 子集。所有字段都是可选的——非 nil 会覆盖原值，nil 保持不变。

**variantId** `String?`

**regulatory** `Regulatory?`

**userEmail** `String?`

**advertisingId** `String?`

**vendorId** `String?`

## `Message`

**id** `String` *required*

消息的唯一 ID。

**role** `Message.Role` *required*

`.user` 或 `.assistant`。

**content** `String` *required*

消息文本。

**createdAt** `Date`

默认 `Date()`。

## `AdOptions`

**code** `String`

Placement code。默认 `"inlineAd"`。

**theme** `String?`

透传给广告 iframe 的 UI 主题（例如 `"dark"`）。

## `AddMessageOptions`

**trackOnly** `Bool`

当为 `true` 时，preload 仍会发出（用于分析），但不会为该消息产生广告。默认 `false`。

## `AdEvent`

`AdEvent` 是一个枚举，每个 case 携带类型化的 payload。每个 case 都有稳定的字符串标识，可通过 `event.name` 访问。

### `.filled(FilledData)` —— wire name `ad.filled`

广告位拿到了一条广告。

**FilledData**

**bidId** `UUID`

**code** `String`

与该广告匹配的 placement code。配置了多个 `enabledPlacementCodes` 的发布方必须根据它区分。

**revenue** `Double?`

### `.noFill(NoFillData)` —— wire name `ad.no-fill`

广告位没有返回广告（服务端跳过）。

**NoFillData**

**skipCode** `String`

广告被跳过的原因。

### `.adHeight(AdHeightData)` —— wire name `ad.height`

广告 iframe 上报了新的高度。可用于调整外层容器的尺寸（在 UIKit `UITableView` / `UICollectionView` cell 中尤其有用）。

**AdHeightData**

**bidId** `UUID`

**messageId** `String`

**height** `CGFloat`

### `.viewed(ViewedData)` —— wire name `ad.viewed`

广告被用户查看（满足 IAB MRC 可见性标准）。

**ViewedData**

**bidId** `UUID`

**content** `String`

**messageId** `String`

**format** `String`

**revenue** `Double?`

### `.clicked(ClickedData)` —— wire name `ad.clicked`

用户点击了广告。

**ClickedData**

**bidId** `UUID`

**content** `String`

**messageId** `String`

**url** `String`

**format** `String`

**area** `String`

被点击的广告区域。

### `.renderStarted(RenderStartedData)` —— wire name `ad.render-started`

广告内容的第一个 token 已接收。

**RenderStartedData**

**bidId** `UUID`

### `.renderCompleted(RenderCompletedData)` —— wire name `ad.render-completed`

广告内容流式传输完成。

**RenderCompletedData**

**bidId** `UUID`

### `.error(ErrorData)` —— wire name `ad.error`

SDK 在投放广告时遇到错误。

**ErrorData**

**message** `String`

**errCode** `String`

### `.videoStarted(VideoStartedData)` —— wire name `video.started`

**VideoStartedData**

**bidId** `UUID`

### `.videoCompleted(VideoCompletedData)` —— wire name `video.completed`

**VideoCompletedData**

**bidId** `UUID`

### `.rewardGranted(RewardGrantedData)` —— wire name `reward.granted`

在激励广告流程中，当用户满足条件可领取奖励时触发。

**RewardGrantedData**

**bidId** `UUID`


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