Skip to main content

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:
dependencies: [
    .package(url: "https://github.com/synheart-ai/synheart-core-sdk-swift.git", from: "1.0.0")
]

Xcode

  1. File > Add Packages…
  2. Enter repository URL: https://github.com/synheart-ai/synheart-core-sdk-swift.git
  3. Select version: 1.0.0 or later
  4. Add to your target

Configuration

Info.plist

Add required usage descriptions:
<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

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(
            enableWear: true,
            enablePhone: true,
            enableBehavior: true
        )
    )

    return true
}

Subscribe to HSI Updates

import Combine

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

    init() {
        Synheart.onHSIUpdate
            .sink { hsi in
                // Affect indicators
                print("Arousal Index: \(hsi.affect.arousalIndex)")
                print("Valence Index: \(hsi.affect.valenceIndex)")

                // Engagement indicators
                print("Engagement Stability: \(hsi.engagement.engagementStability)")
                print("Cognitive Load: \(hsi.engagement.cognitiveLoad)")

                self.currentHSI = hsi
            }
            .store(in: &cancellables)
    }
}

Enable Interpretation Modules

class StateManager {
    @Published var focusEstimate: FocusEstimate?
    @Published var emotionState: EmotionState?
    private var cancellables = Set<AnyCancellable>()

    func enableModules() {
        // Enable Focus tracking
        Synheart.enableFocus()
        Synheart.onFocusUpdate
            .sink { focus in
                print("Focus Score: \(focus.estimate.score)")
                print("State: \(focus.state)")
                self.focusEstimate = focus.estimate
            }
            .store(in: &cancellables)

        // Enable Emotion tracking
        Synheart.enableEmotion()
        Synheart.onEmotionUpdate
            .sink { emotion in
                print("Stress Index: \(emotion.stressIndex)")
                print("Primary Emotion: \(emotion.primaryEmotion)")
                self.emotionState = emotion
            }
            .store(in: &cancellables)
    }
}

Enable Cloud Sync

func enableCloudSync() {
    Synheart.enableCloud(
        config: CloudConfig(
            uploadInterval: TimeInterval(300), // 5 minutes
            requireWifi: true
        )
    )

    Synheart.onCloudSync
        .sink { sync in
            print("Synced \(sync.snapshotCount) snapshots")
            print("Status: \(sync.status)")
        }
        .store(in: &cancellables)
}

Complete Example

SwiftUI View

import SwiftUI
import SynheartCore
import Combine

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

    var body: some View {
        NavigationView {
            ScrollView {
                VStack(spacing: 16) {
                    // HSI State Card
                    GroupBox(label: Text("HSI State").font(.headline)) {
                        if let hsi = viewModel.currentHSI {
                            VStack(alignment: .leading, spacing: 8) {
                                Text("Arousal: \(hsi.affect.arousalIndex, specifier: "%.2f")")
                                Text("Valence: \(hsi.affect.valenceIndex, specifier: "%.2f")")
                                Text("Engagement: \(hsi.engagement.engagementStability, specifier: "%.2f")")
                            }
                            .frame(maxWidth: .infinity, alignment: .leading)
                        } else {
                            Text("Waiting for data...")
                                .foregroundColor(.secondary)
                        }
                    }

                    // Focus Card
                    GroupBox(label: Text("Focus").font(.headline)) {
                        if let focus = viewModel.focusEstimate {
                            VStack(alignment: .leading, spacing: 8) {
                                Text("Score: \(focus.score, specifier: "%.2f")")
                                Text("Confidence: \(focus.confidence, specifier: "%.2f")")
                                ProgressView(value: focus.score)
                            }
                            .frame(maxWidth: .infinity, alignment: .leading)
                        } else {
                            Text("Waiting for data...")
                                .foregroundColor(.secondary)
                        }
                    }

                    // Emotion Card
                    GroupBox(label: Text("Emotion").font(.headline)) {
                        if let emotion = viewModel.emotionState {
                            VStack(alignment: .leading, spacing: 8) {
                                Text("Stress: \(emotion.stressIndex, specifier: "%.2f")")
                                Text("Energy: \(emotion.energyLevel, specifier: "%.2f")")
                                Text("State: \(emotion.primaryEmotion)")
                            }
                            .frame(maxWidth: .infinity, alignment: .leading)
                        } else {
                            Text("Waiting for data...")
                                .foregroundColor(.secondary)
                        }
                    }
                }
                .padding()
            }
            .navigationTitle("Human State Monitor")
        }
    }
}

class HumanStateViewModel: ObservableObject {
    @Published var currentHSI: HSIState?
    @Published var focusEstimate: FocusEstimate?
    @Published var emotionState: EmotionState?

    private var cancellables = Set<AnyCancellable>()

    init() {
        initializeSynheart()
        setupSubscriptions()
    }

    private func initializeSynheart() {
        Synheart.initialize(
            userId: "user_123",
            config: SynheartConfig(
                enableWear: true,
                enablePhone: true,
                enableBehavior: true
            )
        )

        Synheart.enableFocus()
        Synheart.enableEmotion()
    }

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

        Synheart.onFocusUpdate
            .receive(on: DispatchQueue.main)
            .sink { [weak self] focus in
                self?.focusEstimate = focus.estimate
            }
            .store(in: &cancellables)

        Synheart.onEmotionUpdate
            .receive(on: DispatchQueue.main)
            .sink { [weak self] emotion in
                self?.emotionState = emotion
            }
            .store(in: &cancellables)
    }

    deinit {
        Synheart.dispose()
    }
}

HSI State Reference

public struct HSIState {
    public let affect: AffectState
    public let engagement: EngagementState
    public let window: TimeWindow
    public let stateEmbedding: [Double]
    public let timestamp: Date
}

public struct AffectState {
    public let arousalIndex: Double    // 0.0-1.0
    public let valenceIndex: Double    // -1.0 to 1.0
    public let intensity: Double       // 0.0-1.0
}

public struct EngagementState {
    public let engagementStability: Double // 0.0-1.0
    public let cognitiveLoad: Double       // 0.0-1.0
    public let attentionLevel: Double      // 0.0-1.0
}

Focus Module

// Enable focus tracking
Synheart.enableFocus()

Synheart.onFocusUpdate
    .sink { focus in
        switch focus.state {
        case .focused:
            showNotification("You're in the zone!")
        case .distracted:
            showNotification("Take a break?")
        case .deepFocus:
            showNotification("Deep focus detected")
        case .neutral:
            break
        }
    }
    .store(in: &cancellables)

// Disable when done
Synheart.disableFocus()

Emotion Module

// Enable emotion tracking
Synheart.enableEmotion()

Synheart.onEmotionUpdate
    .sink { emotion in
        if emotion.stressIndex > 0.7 {
            triggerStressAlert()
        }

        print("Stress: \(emotion.stressIndex)")
        print("Energy: \(emotion.energyLevel)")
        print("Primary: \(emotion.primaryEmotion)")
    }
    .store(in: &cancellables)

// Disable when done
Synheart.disableEmotion()

Cloud Connector

// Enable cloud sync
Synheart.enableCloud(
    config: CloudConfig(
        uploadInterval: 300, // 5 minutes
        requireWifi: true,
        batchSize: 100
    )
)

Synheart.onCloudSync
    .sink { sync in
        switch sync.status {
        case .success:
            print("Uploaded \(sync.snapshotCount) snapshots")
        case .failed:
            print("Sync failed: \(sync.error ?? "Unknown error")")
        case .inProgress:
            print("Syncing...")
        }
    }
    .store(in: &cancellables)

// Manual sync trigger
Synheart.syncNow()

// Disable cloud sync
Synheart.disableCloud()

Configuration Options

let config = SynheartConfig(
    // Module enables
    enableWear: true,
    enablePhone: true,
    enableBehavior: true,

    // Update intervals
    hsiUpdateInterval: 30, // seconds

    // Capability level (default: .core)
    capabilityLevel: .core,

    // Debug mode
    debug: false
)

Synheart.initialize(
    userId: "user_123",
    config: config
)

Error Handling

do {
    try 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)")
}
// Check consent status
let consentStatus = Synheart.getConsentStatus()
print("Wear module: \(consentStatus.wear)")
print("Cloud sync: \(consentStatus.cloud)")

// Request consent
let granted = await Synheart.requestConsent(
    modules: [.wear, .cloud],
    reason: "We need access to provide personalized insights"
)

if granted {
    Synheart.enableCloud()
}

// Revoke consent
Synheart.revokeConsent(.cloud)

Async/Await Support

// Modern async/await API
class StateManager {
    func initialize() async throws {
        try await Synheart.initialize(
            userId: "user_123",
            config: config
        )

        await Synheart.enableFocus()
        await Synheart.enableEmotion()
    }

    func monitorState() async {
        for await hsi in Synheart.onHSIUpdate.values {
            print("New HSI state: \(hsi)")
        }
    }
}

Background Updates

// Enable background delivery (iOS only)
Synheart.enableBackgroundDelivery(
    frequency: .immediate
)

// Handle background updates
class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication,
                     performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

        Synheart.processBackgroundUpdate { result in
            switch result {
            case .success:
                completionHandler(.newData)
            case .failure:
                completionHandler(.failed)
            }
        }
    }
}

API Reference

Synheart

Main SDK class. Static Methods:
MethodDescriptionReturns
initialize()Initialize the SDKVoid
enableFocus()Enable focus moduleVoid
enableEmotion()Enable emotion moduleVoid
enableCloud()Enable cloud syncVoid
dispose()Cleanup resourcesVoid
Publishers:
PublisherTypeDescription
onHSIUpdateAnyPublisher<HSIState, Never>HSI state updates
onFocusUpdateAnyPublisher<FocusUpdate, Never>Focus estimates
onEmotionUpdateAnyPublisher<EmotionState, Never>Emotion states
onCloudSyncAnyPublisher<SyncEvent, Never>Cloud sync events

Resources


Author: Israel Goytom