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

# Implementação

> Como implementar a verificação de liveness na sua aplicação iOS

## Uso Básico

Após [instalar e configurar](/plataforma/liveness/hub/sdk/ios/installation) o SDK, você pode iniciar a verificação de liveness com poucas linhas de código.

### Exemplo Completo com SwiftUI

```swift theme={"theme":"catppuccin-latte"}
import SwiftUI
import HubLivenessSDK
import AVFoundation

struct LivenessView: View {
    @State private var isLoading = false
    @State private var resultMessage: String?
    @State private var showPermissionAlert = false

    var body: some View {
        VStack(spacing: 24) {
            Button(action: checkPermissionAndStart) {
                HStack {
                    if isLoading {
                        ProgressView()
                            .tint(.white)
                    }
                    Text(isLoading ? "Verificando..." : "Iniciar Liveness")
                }
                .frame(maxWidth: .infinity)
                .padding()
                .background(Color.blue)
                .foregroundColor(.white)
                .cornerRadius(12)
            }
            .disabled(isLoading)

            if let message = resultMessage {
                Text(message)
                    .padding()
            }
        }
        .padding()
        .alert("Permissão Necessária", isPresented: $showPermissionAlert) {
            Button("OK") {}
        } message: {
            Text("Habilite a câmera nas configurações do app.")
        }
    }

    private func checkPermissionAndStart() {
        switch AVCaptureDevice.authorizationStatus(for: .video) {
        case .authorized:
            startLivenessVerification()
        case .notDetermined:
            AVCaptureDevice.requestAccess(for: .video) { granted in
                DispatchQueue.main.async {
                    if granted {
                        startLivenessVerification(riskLevel: .low)
                    } else {
                        showPermissionAlert = true
                    }
                }
            }
        default:
            showPermissionAlert = true
        }
    }

    private func startLivenessVerification(riskLevel: HubRiskLevel) {
        isLoading = true
        resultMessage = nil

        Task {
            do {
                try await HubLiveness.shared.startLiveness(
                    riskLevel: riskLevel
                ) { result in
                    Task { @MainActor in
                        isLoading = false

                        switch result {
                        case .success(let data):
                            resultMessage = "Verificação concluída! Score: \(data.livenessScore ?? 0)"

                        case .failure(let error):
                            resultMessage = "Erro: \(error.localizedDescription)"

                        case .cancelled:
                            resultMessage = "Verificação cancelada"
                        }
                    }
                }
            } catch {
                await MainActor.run {
                    isLoading = false
                    resultMessage = "Erro: \(error.localizedDescription)"
                }
            }
        }
    }
}
```

## Níveis de Risco

O SDK oferece três níveis de segurança para a detecção de liveness:

```swift theme={"theme":"catppuccin-latte"}
/// Risk level for liveness detection
public enum HubRiskLevel : String, Sendable, CaseIterable, Codable {

    case low

    case medium

    case high
}
```

### HubResult

O resultado da verificação é retornado através do enum `HubResult`:

```swift theme={"theme":"catppuccin-latte"}
public enum HubResult: Sendable {
    case success(HubSuccessData)
    case failure(HubError)
    case cancelled
}
```

### HubSuccessData

Em caso de sucesso, você recebe os seguintes dados:

```swift theme={"theme":"catppuccin-latte"}
public struct HubSuccessData: Sendable {
    public let faceImage: Data        // Imagem facial capturada
    public let livenessScore: Double? // Score de liveness
    public let sessionId: String?     // ID da sessão no backend
    public let metadata: [String: String] // Metadados adicionais
}
```

### HubError

Em caso de falha, você recebe um erro tipado:

```swift theme={"theme":"catppuccin-latte"}
public enum HubError: Error, Sendable {
    case notInitialized
    case invalidConfiguration
    case cameraPermissionDenied
    case userCancelled
    case timeout
    case livenessCheckFailed(reason: String)
    case networkError(String)
    case unknownError(String)
}
```

### Resumo das Classes Principais

| Classe            | Tipo   | Descrição                           |
| ----------------- | ------ | ----------------------------------- |
| `HubLiveness`     | class  | Singleton - ponto de entrada do SDK |
| `HubConfig`       | struct | Configuração do SDK                 |
| `HubRiskLevel`    | enum   | Níveis de risco para detecção       |
| `HubResult`       | enum   | Resultado da verificação            |
| `HubSuccessData`  | struct | Dados de sucesso                    |
| `HubError`        | enum   | Erros tipados                       |
| `HubLocalization` | struct | Configuração de idioma              |

### Referência Rápida

```swift theme={"theme":"catppuccin-latte"}
// Inicialização
try await HubLiveness.shared.initialize(config: HubConfig)

// Verificação de Liveness
try await HubLiveness.shared.startLiveness(
    riskLevel: HubRiskLevel,
    onCompletion: (HubResult) -> Void
)
```

## Próximos Passos

<CardGroup cols={2}>
  <Card title="Customização" icon="palette" href="/plataforma/liveness/hub/sdk/ios/customization">
    Personalize idiomas e textos
  </Card>

  <Card title="Troubleshooting" icon="wrench" href="/plataforma/liveness/hub/sdk/ios/troubleshooting">
    Resolução de problemas comuns
  </Card>
</CardGroup>
