Mobile SDK Quickstart
Sync a user's Apple Health data to Sonar from your iOS app, then read it from your backend.
In about an hour, your app will ask the user for Apple Health access and sync their data in the background, and your backend will read it through the Sonar API. Everything here runs in the sandbox environment. The sonar-sdk-examples repository has the finished result: a Swift app, an Expo app, and a small backend.
How It Fits Together
- 1 Your app → Your backend Ask for a client token
- 2 Your backend → Sonar Create a client token (API key)
- 3 Your backend → Your app Return the client token
- 4 Your app → Sonar Apple Health data, straight to Sonar
- 5 Sonar → Your backend subject.synced webhook
- 6 Your backend → Sonar Read the data (API key)
- 7 Your backend → Your app Serve it through your own API
Health data goes from the phone straight to Sonar. Your backend is the only part that holds the API key: it hands the app a short-lived token and reads the processed data. The app never reads from Sonar directly.
Before You Start
- Access to the Developers workspace in Atlas.
- A backend you can add a route to. The examples use TypeScript; any language that makes HTTPS calls works.
- A Swift app built with Xcode 26 or later, or an Expo app on Expo SDK 54 or later.
- An iPhone with data in the Health app. The simulator’s Health app starts empty.
Part 1: Set Up Atlas
Create a Sandbox API Key
In Atlas, open Developers → API Keys, select Create key, and choose the Sandbox environment. Store the key on your backend as SONAR_API_KEY: Atlas shows it only once.
Register Your App
Switch Atlas to Sandbox, open Developers → Apps → Mobile apps, and select Add app. Enter a name, choose iOS, and paste your bundle ID exactly as it appears in Xcode (Target → General → Bundle Identifier) or in ios.bundleIdentifier of your Expo config.
Atlas gives the app an app ID, such as app_Qm3t8Vx1LmN0aB7cD9eF2g, with a copy button next to it. The app ID is not a secret; your app needs it in Part 3.
The API key, the app ID and your Sonar users always belong to one environment. When you go live, you create a live key and register the app again in Live, which gives it a new app ID.
Part 2: Prepare Your Backend
Create a Sonar User for Each of Your Users
The first time one of your users connects Apple Health, create a Sonar user and save its id next to your own user record. external_ref is your own ID for them.
curl "https://atlas.sonarhealth.co/v1/users" \
-X POST \
-H "Authorization: Bearer $SONAR_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "external_ref": "member_123", "display_name": "Jordan Kim" }'{
"id": "7e4e91a5-1e4f-4fc2-903c-251046d2a4d3",
"external_ref": "member_123",
"display_name": "Jordan Kim",
"created_at": "2026-09-14T09:30:00.000Z"
}Create each Sonar user once and reuse its id from then on, not one per phone or per sign-in.
Add a Client-Token Route
Your app calls this route while its user is signed in. The route works out which Sonar user that is and asks Sonar for a client token:
import { randomUUID } from "node:crypto";
const SONAR_API = "https://atlas.sonarhealth.co/v1";
// POST /sonar/client-token, called by your app with its normal sign-in
export async function createSonarClientToken(request: Request) {
const user = await requireSignedInUser(request);
const sonarUserId = await sonarUserIdFor(user);
const { appId, installationId } = await request.json();
const response = await fetch(`${SONAR_API}/users/${sonarUserId}/sdk-sessions`, {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.SONAR_API_KEY}`,
"Content-Type": "application/json",
"Idempotency-Key": randomUUID(),
},
body: JSON.stringify({ app_id: appId, installation_id: installationId }),
});
if (!response.ok) throw new Error(`Sonar returned ${response.status}`);
const { client_token } = await response.json();
return Response.json({ client_token });
}requireSignedInUser is your own sign-in check, and sonarUserIdFor looks up the ID you saved in the previous step. The SDK supplies appId and installationId; pass them through unchanged. A client token is single use and lasts five minutes, so the app asks for a fresh one whenever the SDK needs it.
Never trust a user ID sent by the app
Work out the Sonar user from the user signed in to your backend, never from a value in the request body. Otherwise one user could get a token for another user’s account.
Part 3: Add the SDK to Your App
Install the SDK
In Xcode, select File → Add Package Dependencies…, enter https://github.com/Sonar-Health/sonar-ios-sdk, choose version 0.1.3 or later, and add the SonarSDK product to your app target. CocoaPods works too.
npx expo install @sonarhealth/react-native-sdkAllow Apple Health and Background Work
In your target’s Signing & Capabilities, add HealthKit with Background Delivery checked, and Background Modes with Background fetch and Background processing checked. Then add two keys to the Info tab:
<key>NSHealthShareUsageDescription</key>
<string>We read your health data to show your activity, sleep and vitals.</string>
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
<string>co.sonarhealth.sdk.refresh</string>
<string>co.sonarhealth.sdk.backfill</string>
</array>The usage description is what iPhone shows when it asks the user for Health access, so write it for them.
Add the config plugin with your app ID. At build time it adds the HealthKit capability, the background modes and the Info.plist keys, and it configures the SDK when the app launches.
{
"expo": {
"plugins": [
[
"@sonarhealth/react-native-sdk",
{
"appId": "app_Qm3t8Vx1LmN0aB7cD9eF2g",
"healthShareUsageDescription": "We read your health data to show your activity, sleep and vitals."
}
]
]
}
}healthShareUsageDescription is what iPhone shows when it asks the user for Health access, so write it for them. Build with npx expo run:ios or EAS; Expo Go cannot load the SDK.
Configure the SDK at Launch
Call configure with your app ID in your app delegate, on every launch, whether or not anyone is signed in. iOS runs background syncs only for work registered while the app is launching, so it has to happen here.
import SonarSDK
import UIKit
final class AppDelegate: NSObject, UIApplicationDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
try? Sonar.configure(appId: "app_Qm3t8Vx1LmN0aB7cD9eF2g")
return true
}
}In a SwiftUI app, attach it with @UIApplicationDelegateAdaptor(AppDelegate.self).
Nothing to do: the config plugin configures the SDK natively at every launch, before any JavaScript runs.
Authenticate When Your User Is Signed In
Call authenticate as soon as your app knows who is signed in: right after sign-in, whenever that happens, and at launch once your app has restored a signed-in user. Pass your own ID for the user and a function that calls the route from Part 2.
try await Sonar.authenticate(userId: currentUser.id) { context in
try await myBackend.sonarClientToken(
appId: context.appId,
installationId: context.installationId
)
}import { Sonar } from "@sonarhealth/react-native-sdk";
await Sonar.authenticate({
userId: currentUser.id,
clientTokenProvider: async ({ appId, installationId }) => {
const response = await myBackend.sonarClientToken({ appId, installationId });
return response.client_token;
},
});The first time, the SDK trades the token for its own session and keeps it on the phone, so later launches usually skip your backend entirely. It keeps your function only in memory and needs it to renew a session that ended, which is why the call belongs in every launch. If a different user signs in on the same phone, the SDK signs the previous one out first.
Add a “Connect Apple Health” Button
Watch the SDK state, and connect when the user taps your button:
let observation = Sonar.observeState { state in
render(state.providers.first { $0.provider == .appleHealth })
}
// When the user taps "Connect Apple Health"
try await Sonar.connect(.appleHealth)import { Platform } from "react-native";
const unsubscribe = Sonar.observeState((state) => {
render(state.providers.find((p) => p.provider === "apple_health"));
});
// When the user taps "Connect Apple Health"
if (Platform.OS === "ios") {
await Sonar.connect("apple_health");
}connect opens the Apple Health permission sheet, registers the connection with Sonar and returns; the import carries on in the background. The state drives your UI: connection becomes connected, synchronization shows when a sync runs, and backfill.fraction climbs from 0 to 1 as history arrives. Every field is in the SDK Interface.
Part 4: Check That It Works
Connect on an iPhone
Sign in to your app, tap your button, and allow the Health types. The SDK sends the last 30 days first, then works back through the history period, two years by default. Keeping the app open for the first minutes speeds this up.
Find the User in Atlas
Open Developers → Users in Sandbox and select your user. Apple Health shows as connected, with when it last synced and when the phone was last seen.
Read the Data
curl "https://atlas.sonarhealth.co/v1/users/7e4e91a5-1e4f-4fc2-903c-251046d2a4d3/daily?types=steps,resting_heart_rate&from_date=2026-09-13&to_date=2026-09-14" \
-H "Authorization: Bearer $SONAR_API_KEY"Data is readable shortly after the SDK sends it, once Sonar has processed it. Daily Data, Sleep, Workouts and Timeseries cover the other reads.
Part 5: Finish the Integration
Know when new data arrives. Subscribe your backend to subject.synced in Developers → Webhooks. Sonar sends it each time it has processed new data for a user, with the dates and data types to read again. Expect several after a first connect, as history arrives. See Webhooks.
Sign out with your user. When your user signs out of your app, call Sonar.signOut(). The SDK stops syncing and ends its session; the data already in Sonar stays. When the same user signs in again, authenticate picks the sync up where it stopped. Do not call signOut at launch or before authenticate: at launch, authenticate alone keeps the session going.
Go live. Create a Live API key for your production backend, register the app in Live and build your release with that app ID, and declare health data in your App Privacy answers (Privacy and App Store).
If Something Goes Wrong
| What you see | Likely cause | Fix |
|---|---|---|
connect fails with provider_configuration_required |
The HealthKit capability or the usage description is missing | Redo Allow Apple Health and Background Work and rebuild |
Your token route gets 404 not_found |
The API key, app ID and Sonar user are not in the same environment | Use sandbox for all three, or live for all three |
Your token route gets 403 sdk_application_disabled |
The app is disabled in Atlas | Enable it in Developers → Apps |
authenticate fails with client_token_unavailable |
Your token function threw, or your route failed | Check your backend logs |
| Connected, but no data | The simulator has no Health data, or the user allowed no types | Test on an iPhone with data. iOS never says which types were refused |
Sonar.sendDiagnostics() uploads the SDK’s own log and returns a receipt ID to quote when you contact us.
Sonar