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

# Referencia del SDK de tiempo real de Swift

> Conéctese a través de Socket.IO, suscríbase a canales, publique eventos, rastree la presencia y maneje reconexiones con el cliente de tiempo real de Swift de InsForge en Apple.

## Instalación

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>

## Modelo mental

El SDK de Swift se conecta a InsForge Realtime a través de Socket.IO. Suscríbase a nombres de canal como `order:123` o `chat:room-1`, luego escuche nombres de eventos publicados en esos canales.

Los eventos se publican mediante disparadores de base de datos que llaman a `realtime.publish(...)` o mediante clientes que publican en un canal al que ya se han unido. Consulte [Descripción general de Realtime](/core-concepts/realtime/overview) para el modelo de canal y RLS.

## Inicio rápido

```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()

Establece una conexión en tiempo real.

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

## subscribe()

Suscríbase a un canal y reciba mensajes publicados en él.

```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)")
    }
}
```

Si RLS está habilitado en `realtime.channels`, la suscripción se verifica con las políticas `SELECT`.

## publish()

Publique un evento en un canal.

```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>
  El cliente debe suscribirse a un canal antes de publicar en ese canal.
</Note>

Si RLS está habilitado en `realtime.messages`, la publicación también se verifica con las políticas `INSERT`.

## unsubscribe()

Abandone un canal.

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

## disconnect()

Cierre la conexión en tiempo real.

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

## API de canal

El API de canal agrupa operaciones para un nombre de canal.

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

### Mensajes de difusión

Escucha un evento:

```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)")
}
```

Publicar a través del canal:

```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)
)
```

Elimine un objeto de canal cuando ya no sea necesario:

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

## Presencia

Las suscripciones exitosas devuelven la instantánea de presencia actual cuando lo admite el API del SDK. Escuche las actualizaciones de presencia a través del canal o las API de eventos de nivel inferior expuestas por el SDK.

La presencia es un estado en línea efímero. No se almacena en Postgres.
