Skip to main content

Introduction

The Open Wearables iOS SDK (OpenWearablesHealthSDK) is a native Swift SDK for secure background synchronization of health data from Apple HealthKit to the Open Wearables platform. This is the core native implementation that powers health data sync on iOS. The Flutter SDK uses this SDK under the hood as a wrapper.

GitHub Repository

View source code, report issues, and contribute to the iOS SDK.

Features

  • Background Sync - Health data syncs even when your app is in the background via HealthKit observer queries and BGTaskScheduler
  • Streaming Sync - Memory-efficient streaming processing for large datasets
  • Resumable Sessions - Sync sessions survive app restarts and device reboots
  • Dual Authentication - Token-based auth with auto-refresh or API key authentication
  • Secure Storage - Credentials stored in iOS Keychain with kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
  • Automatic Retry - Persistent outbox with retry logic for failed uploads
  • Per-User Isolation - State isolation between different user sessions
  • Network Monitoring - Connectivity-aware sync with automatic resume
  • Wide Data Support - Steps, heart rate, workouts, sleep, and 40+ data types

Requirements

RequirementDetails
iOS VersioniOS 15.0+
SwiftSwift 5.0+ (Swift tools 5.9)
XcodeXcode 15+
Apple Developer AccountRequired for HealthKit entitlement
HealthKit CapabilityMust be enabled in Xcode
Physical DeviceHealthKit doesn’t work in iOS Simulator

Installation

Add the package to your Package.swift:
dependencies: [
    .package(url: "https://github.com/the-momentum/OpenWearablesHealthSDK.git", from: "0.8.0")
]
Or in Xcode: FileAdd Package Dependencies → paste the repository URL.

iOS Configuration

Add the following to your Info.plist:
<!-- Health data permission -->
<key>NSHealthShareUsageDescription</key>
<string>This app syncs your health data to your account.</string>

<!-- Background modes for sync -->
<key>UIBackgroundModes</key>
<array>
    <string>fetch</string>
    <string>processing</string>
</array>

<!-- Background task identifiers -->
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
    <string>com.openwearables.healthsdk.task.refresh</string>
    <string>com.openwearables.healthsdk.task.process</string>
</array>
Then enable HealthKit capability in Xcode:
  1. Open your .xcodeproj or .xcworkspace in Xcode
  2. Select your target → Signing & Capabilities
  3. Click + Capability → Add HealthKit
  4. Check Background Delivery if you want updates while app is closed

Quick Start

Here’s the minimal code to get health sync working:
import OpenWearablesHealthSDK

class HealthService {
    let sdk = OpenWearablesHealthSDK.shared

    func initialize() {
        // 1. Set up logging (optional)
        sdk.onLog = { message in
            print("[Health] \(message)")
        }

        // 2. Set log level (optional — default is .debug)
        sdk.setLogLevel(.always)

        // 3. Handle auth errors (optional)
        sdk.onAuthError = { statusCode, message in
            print("Auth error: \(statusCode) - \(message)")
        }

        // 4. Configure the SDK with your host
        sdk.configure(host: "https://api.openwearables.io")

        // 5. Check if already signed in (session restored from Keychain)
        if sdk.isSessionValid {
            print("Session restored")
            return
        }

        // 6. Get credentials from YOUR backend, then sign in
        let credentials = yourBackend.getHealthCredentials()

        sdk.signIn(
            userId: credentials.userId,
            accessToken: credentials.accessToken,
            refreshToken: credentials.refreshToken,
            apiKey: nil
        )

        // 7. Request health permissions
        sdk.requestAuthorization(types: [.steps, .heartRate, .sleep, .workout]) { granted in
            if granted {
                // 8. Start background sync (sync last 90 days of data)
                sdk.startBackgroundSync(syncDaysBack: 90) { started in
                    print("Sync started: \(started)")
                }
            }
        }
    }
}

AppDelegate Setup

For background URL session support, add to your AppDelegate:
func application(
    _ application: UIApplication,
    handleEventsForBackgroundURLSession identifier: String,
    completionHandler: @escaping () -> Void
) {
    OpenWearablesHealthSDK.setBackgroundCompletionHandler(completionHandler)
}

Documentation

Integration Guide

Complete guide to integrating the SDK including authentication flow, backend setup, and best practices.

Troubleshooting

Common issues and their solutions for native iOS.

Supported Health Data Types

The SDK supports 40+ health data types via the HealthDataType enum. Pass these as enum values to requestAuthorization(types:completion:):
sdk.requestAuthorization(types: [.steps, .heartRate, .sleep, .workout]) { granted in
    // ...
}
Enum CaseDescription
.stepsStep count
.distanceWalkingRunningWalking/running distance
.distanceCyclingCycling distance
.flightsClimbedFloors climbed
.walkingSpeedAverage walking speed
.walkingStepLengthStep length
.walkingAsymmetryPercentageWalking asymmetry percentage
.walkingDoubleSupportPercentageWalking double support percentage
.sixMinuteWalkTestDistance6-minute walk test
.activeEnergyActive energy burned
.basalEnergyBasal (resting) energy burned
Enum CaseDescription
.heartRateHeart rate measurements
.restingHeartRateResting heart rate
.heartRateVariabilitySDNNHRV (SDNN)
.vo2MaxVO2 max
.oxygenSaturationBlood oxygen
.respiratoryRateBreathing rate
Enum CaseDescription
.bodyMassWeight
.heightHeight
.bmiBody Mass Index
.bodyFatPercentageBody fat %
.leanBodyMassLean body mass
.waistCircumferenceWaist circumference (iOS 16+)
.bodyTemperatureBody temperature
Enum CaseDescription
.bloodGlucoseBlood glucose level
.insulinDeliveryInsulin delivery (iOS 16+)
.bloodPressureSystolicSystolic blood pressure
.bloodPressureDiastolicDiastolic blood pressure
.bloodPressureBlood pressure (correlation type)
Enum CaseDescription
.sleepSleep sessions and stages
.mindfulSessionMeditation/mindfulness sessions
Enum CaseDescription
.menstrualFlowMenstrual flow
.cervicalMucusQualityCervical mucus quality
.ovulationTestResultOvulation test result
.sexualActivitySexual activity
Enum CaseDescription
.dietaryEnergyConsumedCalories consumed
.dietaryCarbohydratesCarbs
.dietaryProteinProtein
.dietaryFatTotalTotal fat
.dietaryWaterWater intake
Enum CaseDescription
.workoutAll workout types with metadata (distance, energy, heart rate, running metrics, elevation, weather, swimming)
Enum CaseAlias For
.restingEnergy.basalEnergy
.bloodOxygen.oxygenSaturation

Next Steps

Integration Guide

Complete step-by-step integration guide.

API Reference

Full API documentation on GitHub.