Sonar Developers

iOS (Swift)

Sync your users' Apple Health data to Sonar from your iOS app.

7 min read Updated Sep 24, 2026

Example app

A working app and a demo backend are in sonar-sdk-examples.

The SDK reads Apple Health through HealthKit and sends the data to Sonar for the signed-in user. Your backend then reads the normalized data from the Sonar API. The SDK only reads: it never writes to Apple Health.

After the user connects Apple Health, the SDK syncs on its own: when the app opens, when HealthKit reports new data, and in background tasks. It sends recent days first, then works back through the history period, two years by default. Supported Native Data lists what it reads.

Before You Start

  • An SDK app ID. Add your bundle ID in Atlas → Developers → Apps. Sandbox and live have separate app IDs: build with the one that matches the API key your backend uses.
  • A client-token endpoint on your backend. It calls POST /v1/users/{id}/sdk-sessions with your API key and returns the client_token to the app. See SDK Authentication.
  • A Sonar user for each of your users (POST /v1/users).

The app never holds a Sonar API key.

Requirements

Area Requirement
iOS 16 or later
Xcode 26 or later (the framework is built with Swift 6.3)
Device An iPhone for real testing. The simulator’s Health app has no data unless you add it.

Install

Swift Package Manager

In Xcode, add the package https://github.com/Sonar-Health/sonar-ios-sdk.git, version 0.1.3 or later, and add the SonarSDK product to your app target. In a package manifest:

swift
dependencies: [
    .package(url: "https://github.com/Sonar-Health/sonar-ios-sdk.git", from: "0.1.3")
]

CocoaPods

Point your Podfile at the podspec in the repository:

text
pod 'SonarSDK', :podspec => 'https://raw.githubusercontent.com/Sonar-Health/sonar-ios-sdk/0.1.3/SonarSDK.podspec'

Both install the same prebuilt SonarSDK.xcframework.

Set Up the App Target

Add the capabilities

In Signing & Capabilities, add HealthKit and check Background Delivery. Add Background Modes and check Background fetch and Background processing.

Add the Info.plist keys

NSHealthShareUsageDescription is the text iOS shows in the Health permission sheet. The two task identifiers let the SDK schedule its background work. The SDK does not write to Apple Health, so it does not need NSHealthUpdateUsageDescription.

xml
<key>NSHealthShareUsageDescription</key>
<string>Explain why your app reads health data.</string>
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
    <string>co.sonarhealth.sdk.refresh</string>
    <string>co.sonarhealth.sdk.backfill</string>
</array>
<key>UIBackgroundModes</key>
<array>
    <string>fetch</string>
    <string>processing</string>
</array>

Configure at Launch

Call Sonar.configure(appId:) in application(_:didFinishLaunchingWithOptions:), on every launch, even when no user is signed in yet. iOS keeps background tasks and HealthKit observers only when they are registered before launch finishes.

swift
import SonarSDK
import UIKit

final class AppDelegate: NSObject, UIApplicationDelegate {
    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
    ) -> Bool {
        do {
            try Sonar.configure(appId: "app_Qm3t8Vx1LmN0aB7cD9eF2g")
        } catch {
            print("Sonar configure failed: \(error)")
        }
        return true
    }
}

In a SwiftUI app, attach the delegate with @UIApplicationDelegateAdaptor(AppDelegate.self).

  • configure(appId:historyDays:) sets how many days of history a new connection imports, from 30 to 1825. The default is 730. See History Period.
  • configure throws .configurationConflict when the app ID changed while a user is signed in: call signOut() before switching app IDs. It throws .notConfigured when historyDays is outside 30 to 1825.
  • If configure runs after launch has finished, the SDK does not crash. It writes a line to its diagnostics log and skips background-task registration for that launch.

Authenticate and Connect

Call authenticate as soon as your app knows who is signed in: right after the user signs in, whenever that happens, and at every launch once your app has restored a signed-in user. The SDK keeps its Sonar session in the Keychain, so this usually returns alreadyAuthenticated without a network call. Calling it still matters: it registers the token provider, and the SDK can renew an ended session silently only while one is registered. userId is your own stable ID for the signed-in user. If it differs from the user the session belongs to, the SDK signs the previous user out first, so one user’s data never syncs into another’s account.

swift
import SonarSDK

try await Sonar.authenticate(userId: currentUser.id) { context in
    try await myBackend.sonarClientToken(
        appId: context.appId,
        installationId: context.installationId
    )
}

let observation = Sonar.observeState { state in
    render(state)
}

try await Sonar.connect(.appleHealth)
  • The token provider returns the client_token string your backend got from Sonar.
  • observeState runs on the main actor. It emits the current state at once, then every change. Keep observation alive while you need updates and call observation.cancel() when done.
  • observeWorkouts runs on the main actor after Sonar accepts workouts new on this phone, never for the history import. Register at launch: Apple Health can wake the app in the background to deliver one. See New Workouts.
  • connect shows the HealthKit permission sheet, records the connection in Sonar and starts syncing. Call it after authenticate, from a user action such as a “Connect Apple Health” button.
  • Sonar.state and Sonar.providerState(for: .appleHealth) read the current state without observing. backfill in the provider state gives import progress (fraction is 0 to 1).

Calls

Call What it does
sync() Sends new data now
resync(.appleHealth) Reads and sends the history period again. Deletes nothing
disconnect(.appleHealth) Stops syncing and deletes the user’s Apple Health data in Sonar
signOut() Ends the Sonar session on this phone and clears its credentials. The connection and data stay in Sonar. When the same user signs in again, syncing picks up where it stopped. Call it only when the user signs out of your app
diagnostics() Returns the SDK’s own log, with no health values
sendDiagnostics() Uploads that log to Sonar. Quote the returned receiptId when you contact support.

Failed calls throw SonarSdkError, with a code, a retryable flag and a suggested recoveryAction. The SDK Interface lists every result, state and error.

Permissions

  • The permission sheet asks for every HealthKit type Sonar supports. The user can grant any subset; the SDK syncs what was granted.
  • iOS never tells an app whether the user denied read access. The permission status stays requested, and a denied type looks the same as a type with no data. Do not tell the user they denied access based on empty data.
  • iOS shows the permission sheet only once per type. To change permissions later, the user goes to Settings → Privacy & Security → Health → your app.

Limits

  • Deletions. Records deleted in Apple Health stay in Sonar. See Edits and Deletions.
  • Edits. Edits to data from about the last week reach Sonar on their own. For older edits, call resync(.appleHealth).
  • One installation per user. One app installation syncs Apple Health for a user. If the same user connects on another phone, that phone takes over and the old one stops syncing.
  • Locked phone. iOS hides Health data while the phone is locked. Syncs wait for the next unlock.
  • Background timing. iOS decides when background tasks and HealthKit wake-ups run. Neither runs on a fixed schedule.

Privacy and App Store

The framework ships a privacy manifest (PrivacyInfo.xcprivacy). It declares:

  • Collected data: health, fitness and other diagnostic data, linked to the user, used for app functionality, not for tracking.
  • Required-reason APIs: UserDefaults (CA92.1) and file timestamps (C617.1).

Xcode merges it into your app’s privacy report. You still own the App Store submission:

  • Declare health and fitness data in your App Privacy answers in App Store Connect, together with what the rest of your app collects.
  • Publish a privacy policy that covers the health data. Apple requires one for apps that use HealthKit.
  • Explain in NSHealthShareUsageDescription what your app does with the data.