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

# Synheart Core - iOS/Swift SDK

> Unified SDK for human-state intelligence in iOS applications

## Overview

The Synheart Core iOS/Swift SDK provides a unified API for collecting HSI-compatible data, processing human state on-device, and generating focus/emotion signals in native iOS applications.

**Key Features:**

* Native iOS support
* On-device HSI Runtime
* Combine framework integration
* Real-time state updates
* Privacy-first architecture

## Installation

### Swift Package Manager

Add to your `Package.swift`:

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

### Xcode

1. File > Add Packages...
2. Enter repository URL: `https://github.com/synheart-ai/synheart-core-swift.git`
3. Select version: `0.0.4` or later (match the dependency entry above)
4. Add to your target

## Configuration

### Info.plist

Add required usage descriptions:

```xml theme={null}
<key>NSHealthShareUsageDescription</key>
<string>This app needs access to your health data to provide insights.</string>

<key>NSMotionUsageDescription</key>
<string>This app uses motion data to understand your activity patterns.</string>
```

### Capabilities

Enable required capabilities in Xcode:

1. Select your target
2. Go to "Signing & Capabilities"
3. Add "HealthKit" (if using Wear module)

## Basic Usage

### Initialize the SDK

```swift theme={null}
import SynheartCore

// Initialize in AppDelegate or App struct
func application(_ application: UIApplication,
                 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    Synheart.initialize(
        userId: "anon_user_123",
        config: SynheartConfig(
            allowUnsignedCapabilities: true  // Use capabilityToken in production
        )
    )

    return true
}
```

### Subscribe to HSI Updates

```swift theme={null}
import Combine

class HumanStateViewModel: ObservableObject {
    @Published var currentHSI: String?
    private var cancellables = Set<AnyCancellable>()

    init() {
        Synheart.onHSIUpdate
            .sink { hsiJson in
                print("HSI JSON: \(hsiJson)")
                self.currentHSI = hsiJson
            }
            .store(in: &cancellables)
    }
}
```

### Activate features

The `SynheartFeature` enum gates collection by feature. Activation is
one of four conditions a feature needs (consent, capability tier, an
active session — see [Capability System](/synheart-core/capability-system)).

```swift theme={null}
// Available cases:
//   .wear         — biosignals from wearables
//   .behavior     — interaction telemetry
//   .phoneContext — motion / screen / app context
//   .cloud        — HSI upload connector

Synheart.activate(.wear)
Synheart.activate(.cloud)

// Stop a feature without uninitializing the SDK.
Synheart.deactivate(.cloud)
```

State signals (focus, emotion, recovery, etc.) are not separate
features — they're axes inside the HSI JSON emitted by
`Synheart.onHSIUpdate`. Parse the JSON to read them.

## Complete example

### SwiftUI view

```swift theme={null}
import SwiftUI
import SynheartCore
import Combine

struct HumanStateMonitorView: View {
    @StateObject private var viewModel = HumanStateViewModel()

    var body: some View {
        NavigationView {
            ScrollView {
                GroupBox(label: Text("HSI State").font(.headline)) {
                    if let hsiJson = viewModel.currentHSI {
                        Text("HSI: \(String(hsiJson.prefix(100)))")
                            .frame(maxWidth: .infinity, alignment: .leading)
                    } else {
                        Text("Waiting for data…").foregroundColor(.secondary)
                    }
                }
                .padding()
            }
            .navigationTitle("Human State")
        }
    }
}

class HumanStateViewModel: ObservableObject {
    @Published var currentHSI: String?
    private var cancellables = Set<AnyCancellable>()

    init() {
        Task { await bootstrap() }
    }

    @MainActor
    private func bootstrap() async {
        try? await Synheart.initialize(
            userId: "user_123",
            config: SynheartConfig(allowUnsignedCapabilities: true)
        )
        Synheart.activate(.wear)
        Synheart.activate(.behavior)

        Synheart.onHSIUpdate
            .receive(on: DispatchQueue.main)
            .sink { [weak self] hsiJson in self?.currentHSI = hsiJson }
            .store(in: &cancellables)
    }

    deinit { Synheart.dispose() }
}
```

## HSI snapshot reference

The Synheart Runtime emits raw JSON strings via `onHSIUpdate`
(`AnyPublisher<String, Never>`). Parse the JSON to extract fields like
the affect / engagement / activity / context axes. See the
[HSI specification](/hsi/overview) for the wire format.

## Cloud Connector

```swift theme={null}
// Enable cloud sync (requires cloudConfig in SynheartConfig)
Synheart.activate(.cloud)

// Disable cloud sync
Synheart.deactivate(.cloud)
```

## Configuration Options

```swift theme={null}
let config = SynheartConfig(
    allowUnsignedCapabilities: true,  // use capabilityToken in production

    // Cloud configuration (optional).
    cloudConfig: CloudConfig(
        appId: "your_app_id",
        subjectId: "user_123",
        instanceId: "device_abc",
        baseUrl: "https://api.synheart.ai"
    ),

    // Capability JWT (optional, for extended/research access).
    capabilityToken: nil
)

try await Synheart.initialize(
    userId: "user_123",
    config: config
)
```

Authentication for cloud uploads is hardware-backed device ECDSA
(Secure Enclave) per
RFC-AUTH-MOBILE-0001.
The runtime owns request signing via the host's `synheart-auth`
integration — `CloudConfig` does **not** carry shared secrets or
HMAC keys. See [Synheart Auth overview](/synheart-auth/overview) for
the device-identity flow.

## Diagnostics & upload inspection

Use the diagnostics surface to inspect runtime state and force a
flush when consent and network are eligible.

```swift theme={null}
// Live counters / last-error strings.
let diag = Synheart.runtimeDiagnostics()
print(diag)

// Synchronous getters — safe to read from UI code.
let depth = Synheart.uploadQueueLength
let lastMs = Synheart.lastIngestSuccessAtMs

// Manually flush queued snapshots when eligible.
let result = try await Synheart.ingestion.flushIfEligible()
```

## Error handling

```swift theme={null}
do {
    try await Synheart.initialize(userId: userId, config: config)
} catch let error as PermissionDeniedError {
    print("Permission denied: \(error.message)")
} catch let error as InitializationError {
    print("Initialization failed: \(error.message)")
} catch let error as SynheartError {
    print("SDK error: \(error.message)")
} catch {
    print("Unexpected error: \(error)")
}
```

## Privacy & consent

```swift theme={null}
// Coarse status — granted | pending | expired | denied
let status = await Synheart.consentStatus()

// Per-type check (wire strings: biosignals, phoneContext, behavior,
// cloudUpload, vendorSync, research)
let canUpload = try await Synheart.hasConsent("cloudUpload")
let canRead   = try await Synheart.hasConsent("biosignals")

// Request consent — opens the cloud consent flow when configured.
let token = try await Synheart.requestConsent()

// Revoke a single type or everything.
try await Synheart.revokeConsentType("cloudUpload")
try await Synheart.revokeConsent()
```

See [Consent System](/synheart-core/consent-system) for the full consent model.

## Async/await

```swift theme={null}
class StateManager {
    func bootstrap() async throws {
        try await Synheart.initialize(userId: "user_123", config: config)
        Synheart.activate(.wear)
    }

    func monitorState() async {
        for await hsiJson in Synheart.onHSIUpdate.values {
            print("HSI JSON: \(hsiJson)")
        }
    }
}
```

## API reference

### `Synheart`

Main SDK class.

**Static methods:**

| Method            | Description                             | Returns               |
| ----------------- | --------------------------------------- | --------------------- |
| `initialize(...)` | Initialize the SDK                      | `Void` (async throws) |
| `activate(_:)`    | Activate a `SynheartFeature`            | `Void`                |
| `deactivate(_:)`  | Deactivate a `SynheartFeature`          | `Void`                |
| `dispose()`       | Tear down the SDK and release resources | `Void`                |

**Publishers:**

| Publisher     | Type                          | Description                                |
| ------------- | ----------------------------- | ------------------------------------------ |
| `onHSIUpdate` | `AnyPublisher<String, Never>` | Raw HSI 1.3 JSON, emitted per window close |

## Resources

* **Repository**: [synheart-core-swift](https://github.com/synheart-ai/synheart-core-swift)
* **Documentation**: [API Reference](https://synheart-ai.github.io/synheart-core-swift/)
* **Issues**: [GitHub Issues](https://github.com/synheart-ai/synheart-core-swift/issues)

## Related Documentation

* [HSV Specification](/synheart-core/hsv-specification) - Understand Synheart Core’s internal state model
* [Architecture](/synheart-core/architecture) - Deep dive into the system
* [Capability System](/synheart-core/capability-system) - Access levels and permissions
