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

# Swift 即時 SDK 參考

> 透過 Socket.IO 連線、訂閱頻道、發佈事件、追蹤狀態並在 Apple 上使用 InsForge Swift 即時用戶端處理重新連線。

## 安裝

Add InsForge to your Swift Package Manager dependencies:

```swift theme={null}
dependencies: [
    .package(url: "https://github.com/insforge/insforge-swift.git", from: "0.0.9")
]
```

```swift theme={null}
import InsForge

let insforge = InsForgeClient(
    baseURL: URL(string: "https://your-app.insforge.app")!,
    anonKey: "your-anon-key"
)
```

### Enable Logging (Optional)

For debugging, you can configure the SDK log level and destination:

```swift theme={null}
let options = InsForgeClientOptions(
    global: .init(
        logLevel: .debug,
        logDestination: .osLog,
        logSubsystem: "com.example.MyApp"
    )
)

let insforge = InsForgeClient(
    baseURL: URL(string: "https://your-app.insforge.app")!,
    anonKey: "your-anon-key",
    options: options
)
```

**Log Levels:**

| Level       | Description                                 |
| ----------- | ------------------------------------------- |
| `.trace`    | Most verbose, includes all internal details |
| `.debug`    | Detailed information for debugging          |
| `.info`     | General operational information (default)   |
| `.warning`  | Warnings that don't prevent operation       |
| `.error`    | Errors that affect functionality            |
| `.critical` | Critical failures                           |

**Log Destinations:**

| Destination | Description                                                |
| ----------- | ---------------------------------------------------------- |
| `.console`  | Standard output (print)                                    |
| `.osLog`    | Apple's unified logging system (recommended for iOS/macOS) |
| `.none`     | Disable logging                                            |
| `.custom`   | Provide your own LogHandler factory                        |

<Note>
  Use `.info` or `.error` in production to avoid exposing sensitive data in logs.
</Note>

## 思維模型

Swift SDK 透過 Socket.IO 連線到 InsForge 即時。訂閱頻道名稱，如 `order:123` 或 `chat:room-1`，然後監聽發佈到這些頻道的事件名稱。

事件由資料庫觸發器發佈，這些觸發器呼叫 `realtime.publish(...)` 或由已加入頻道的用戶端發佈。有關頻道和 RLS 模型的詳細資訊，請參閱[即時概覽](/core-concepts/realtime/overview)。

## 快速入門

```swift theme={null}
try await insforge.realtime.connect()

await insforge.realtime.subscribe(to: "order:\\(orderId)") { message in
    if message.eventName == "status_changed" {
        print("Payload: \\(String(describing: message.payload))")
    }
}
```

## connect()

建立即時連線。

```swift theme={null}
do {
    try await insforge.realtime.connect()
    print("Connected to realtime")
} catch {
    print("Connection failed: \\(error)")
}
```

## subscribe()

訂閱頻道並接收發佈到該頻道的訊息。

```swift theme={null}
await insforge.realtime.subscribe(to: "chat:room-1") { message in
    print("Event: \\(message.eventName ?? "")")
    print("Channel: \\(message.channelName ?? "")")

    if let payload = message.payload {
        print("Payload: \\(payload)")
    }
}
```

如果在 `realtime.channels` 上啟用了 RLS，訂閱會根據 `SELECT` 原則進行檢查。

## publish()

發佈事件到頻道。

```swift theme={null}
try await insforge.realtime.publish(
    to: "chat:room-1",
    event: "new_message",
    payload: [
        "text": "Hello from Swift",
        "sentAt": ISO8601DateFormatter().string(from: Date())
    ]
)
```

<Note>
  用戶端必須訂閱頻道才能發佈到該頻道。
</Note>

如果在 `realtime.messages` 上啟用了 RLS，發佈也會根據 `INSERT` 原則進行檢查。

## unsubscribe()

離開頻道。

```swift theme={null}
await insforge.realtime.unsubscribe(from: "chat:room-1")
```

## disconnect()

關閉即時連線。

```swift theme={null}
await insforge.realtime.disconnect()
```

## 頻道 API

頻道 API 為一個頻道名稱分組操作。

```swift theme={null}
let channel = await insforge.realtime.channel("chat:room-1")
try await channel.subscribe()
```

### 廣播訊息

監聽事件：

```swift theme={null}
let channel = await insforge.realtime.channel("chat:room-1")
try await channel.subscribe()

for await message in await channel.broadcast(event: "new_message") {
    print("Payload: \\(message.payload)")
}
```

透過頻道發佈：

```swift theme={null}
struct ChatMessage: Codable {
    let text: String
    let author: String
}

try await channel.broadcast(
    event: "new_message",
    message: ChatMessage(text: "Hello", author: currentUser.name)
)
```

不再需要頻道物件時將其移除：

```swift theme={null}
await insforge.realtime.removeChannel("chat:room-1")
```

## 狀態

成功訂閱會傳回目前的狀態快照，SDK API 支援時。透過頻道或 SDK 公開的較低階事件 API 監聽狀態更新。

狀態是暫時的線上狀態。它不會儲存在 Postgres 中。
