Sonar Developers

SDK Interface

The calls your app makes, the state it shows, and the errors it handles.

9 min read Updated Sep 24, 2026

The iOS SDK and the React Native module implement this interface. The Android SDK, in early access, implements the same one.

Calls

Call What it does
configure(appId, historyDays) Sets your SDK app ID and, optionally, how many days of history a new connection imports (30 to 1825, default 730). Call it at every launch, before anything else, even when no user is signed in
authenticate(userId, clientTokenProvider) Starts or resumes the SDK session for the signed-in user, and signs out the previous user when userId changes. Call it whenever a user is signed in: right after sign-in, and at launch when they are already signed in
connect(provider) Asks for Health permission, connects the provider in Sonar, and starts syncing
disconnect(provider) Stops syncing and deletes the provider’s data from Sonar
sync() Sends new data now, then goes on with unfinished history
resync(provider) Sends the provider’s data again: recent days first, then the rest of the history period. Deletes nothing
observeState(callback) / getState() Current session and provider state, and every change to it
observeWorkouts(callback) Workouts new on this phone, each time Sonar accepts them. Swift and Kotlin only for now
signOut() Ends this installation’s session and clears its credentials. Keeps the connection and the data in Sonar. The same user signing in again picks the sync up where it stopped
diagnostics() Returns the SDK’s own log as text
sendDiagnostics() Uploads that log to Sonar and returns a receipt ID for support
setVerboseDiagnostics(enabled) Adds every Health read to the log. For debugging one device

There is no environment setting. Sandbox or live follows the API key your backend uses to create client tokens, so the same app build works with both.

Swift and React Native Names

Operation Swift React Native
Configure try Sonar.configure(appId:historyDays:) Sonar.configure({ appId, historyDays })
Authenticate try await Sonar.authenticate(userId:clientTokenProvider:) await Sonar.authenticate({ userId, clientTokenProvider })
Connect try await Sonar.connect(.appleHealth) await Sonar.connect("apple_health")
Disconnect try await Sonar.disconnect(.appleHealth) await Sonar.disconnect("apple_health")
Sync try await Sonar.sync() await Sonar.sync()
Resync try await Sonar.resync(.appleHealth) await Sonar.resync("apple_health")
Whole state Sonar.state Sonar.getState()
One provider Sonar.providerState(for: .appleHealth) Sonar.getProviderState("apple_health")
Observe Sonar.observeState { state in … } returns SonarObservation; call cancel() Sonar.observeState(listener) returns an unsubscribe function
New workouts Sonar.observeWorkouts { workouts in … } returns SonarObservation Not yet available
Sign out await Sonar.signOut() await Sonar.signOut()
Diagnostics Sonar.diagnostics(), try await Sonar.sendDiagnostics(), Sonar.setVerboseDiagnostics(_:) Sonar.diagnostics(), await Sonar.sendDiagnostics(), Sonar.setVerboseDiagnostics(enabled)

Swift enum cases are camelCase (.appleHealth, .syncingRecent). Their raw values, and every value in React Native, are the snake_case strings in the tables below (apple_health, syncing_recent). Swift delivers state on the main actor. Swift timestamps are Date; React Native timestamps are ISO 8601 strings.

The provider type also contains health_connect and samsung_health, used by the Android SDK, in early access. On iOS, pass apple_health: connect, disconnect and resync reject the others with unsupported_provider.

Configure and Authenticate

This example uses React Native:

typescript
Sonar.configure({ appId: "app_Qm3t8Vx1LmN0aB7cD9eF2g" });

await Sonar.authenticate({
  userId: currentUser.id,
  clientTokenProvider: async ({ appId, installationId }) => {
    const response = await yourApi.createSonarClientToken({ appId, installationId });
    return response.client_token;
  },
});

The token provider calls your own backend, which creates the client token with your API key. The key never goes into the app. See SDK Authentication.

  • On iOS, call configure in application(_:didFinishLaunchingWithOptions:), whether or not a user is signed in. HealthKit observers and background tasks only work when they are registered before launch finishes. A later configure registers them on the next launch. In React Native the config plugin does this for you.
  • Call authenticate whenever your app has a signed-in user. If the user signs in minutes after launch, call it then. If they are already signed in when the app starts, call it once your app has restored their sign-in. Until then, a phone that is already connected keeps syncing with the session it stored.
  • Call it again at every launch while the user stays signed in. The session survives restarts, but the token provider lives only in memory. Without it, the SDK cannot renew an ended session by itself and reports reauthorization_required.
  • Calling configure again with the same app ID does nothing. A different app ID while a session exists rejects with configuration_conflict: call signOut first.
  • historyDays can change at any time without a sign-out. A connection keeps the period it started with; see History Period.
  • authenticate returns already_authenticated when this installation already holds a session for the same userId. It does not call your token provider then. 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.

Connect and Observe

typescript
const unsubscribe = Sonar.observeState((state) => {
  render(state.session, state.providers);
});

const result = await Sonar.connect("apple_health");

connect shows the Apple Health permission sheet, records the connection in Sonar, and starts syncing. Call unsubscribe() when you no longer need updates. State never contains health records or credentials.

A user can connect Apple Health on one installation at a time. If the same user connects on a new phone, the new phone takes over the connection and its data, and the old phone shows disconnected. See Provider Lifecycle.

New Workouts

observeWorkouts calls you after Sonar accepts workouts that are new on this phone, for example to tell the user their run arrived. The import of past data never calls it. Apple Health can wake the app in the background to deliver a workout, so register when the app launches.

swift
let workouts = Sonar.observeWorkouts { delivered in
    for workout in delivered { notifyNewActivity(workout) }
}
Field Meaning
id The workout’s id in Apple Health or Health Connect. Sonar keeps it as the workout’s own id
activityType The platform’s activity code: HKWorkoutActivityType raw value, or the ExerciseSessionRecord exercise type
isIndoor Whether Apple Health marked it indoor. Health Connect leaves it empty
start, end When the workout started and ended

A workout edited later can arrive again with the same id.

Results

Each call returns once its step is done or scheduled. None waits for the history import or for Sonar to process data.

typescript
type AuthenticationResult = {
  status: "authenticated" | "already_authenticated";
  session: SessionStatus;
};

type ConnectResult = {
  status: "connected" | "already_connected" | "pending_cleanup";
  state: ProviderState;
};

type DisconnectResult = {
  status: "disconnecting" | "disconnected";
  state: ProviderState;
};

type SyncResult = {
  status: "started" | "already_running";
  providers: NativeProvider[];
};

type ResyncResult = {
  status: "started" | "already_running";
  provider: NativeProvider;
};

type SignOutResult = {
  status: "signed_out";
};

type DiagnosticsReceipt = {
  receiptId: string;
  bytes: number;
};
  • authenticate returns when the session is ready.
  • connect returns after the permission sheet closes and Sonar holds the connection. pending_cleanup means an earlier disconnect is still deleting data. The provider stays connecting; call connect again later. The SDK also tries once more on the next app launch.
  • disconnect returns once syncing has stopped and Sonar has accepted the disconnect. disconnecting means Sonar is still deleting the data. disconnected means there was nothing to delete, for example because another installation holds the connection.
  • sync and resync return as soon as the work is scheduled. sync returns already_running when a sync is active; the SDK syncs once more after it. resync returns already_running when an earlier resync has not started yet. Both reject with provider_not_connected when Apple Health is not connected.
  • signOut never fails. It asks Sonar to revoke the session, then clears the SDK’s credentials on the phone, even when Sonar cannot be reached. It keeps where the sync stopped for the same user signing in again, and forgets it as soon as another user signs in.

Lifecycle calls run one at a time, in the order you make them. disconnect and signOut stop the active sync first. Data Sonar has already accepted stays in Sonar after signOut.

Sync, Resync, and Disconnect

Action What it reads Data already in Sonar
Automatic sync New data, then unfinished history Kept
sync() Same, right now Kept
resync(provider) Everything again, over the history period Kept; repeats are skipped
disconnect(provider) Nothing. Syncing stops Deleted

Use sync() when the user expects fresh data, such as when they open a health screen after a workout. Syncing happens without it too.

Use resync(provider) when data looks incomplete, for example after the user grants more Health types in Settings, or to pick up edits to data older than about a week. Sonar skips records it already holds.

Resync does not delete

Only disconnect(provider) removes data from Sonar. To rebuild from scratch, disconnect, wait for the deletion to finish, then connect again.

See SDK Synchronization for when the SDK syncs on its own.

State

typescript
type SonarState = {
  session: SessionStatus;
  providers: ProviderState[];
};

type ProviderState = {
  provider: NativeProvider;
  availability: ProviderAvailability;
  permission: PermissionStatus;
  connection: ConnectionStatus;
  synchronization: SynchronizationStatus;
  recoveryAction: RecoveryAction;
  lastSuccessfulSyncAt: string | null;
  lastDataSentAt: string | null;
  backfill: BackfillProgress | null;
  observedAt: string;
};

type BackfillProgress = {
  phase: "recent" | "history" | "complete";
  daysDone: number;
  daysTotal: number;
  fraction: number;
};

observeState calls you right away with the current state, then on every change. Identical states in a row are not repeated. On iOS, providers holds one entry, for apple_health. On Android, the React Native module returns signed_out with an empty providers list.

  • lastSuccessfulSyncAt is when the SDK last finished a sync without errors, including one that found nothing new.
  • lastDataSentAt is when the SDK last delivered new records or deletions. A sync that finds nothing new leaves it as it was, so when lastSuccessfulSyncAt moves and lastDataSentAt does not, Sonar has nothing new to process.
  • backfill tracks the history import: daysTotal is the connection’s history period (730 by default), phase moves from recent (the last 30 days) to history to complete, and fraction goes from 0 to 1 for a progress bar. It is null before the first sync.
  • observedAt is when this provider’s state last changed.

Session Status

Value Meaning
signed_out No session. Call authenticate
ready The session works
refreshing The SDK is getting a new session through your token provider
temporarily_unavailable Sonar could not start a session. It can be retried
reauthorization_required The session ended and could not be renewed. Call authenticate

Provider Availability

Value Meaning
available The device has Apple Health
unavailable The device has no Apple Health, for example an iPad before iPadOS 17
unknown, install_required, update_required, configuration_required Not reported on iOS. Used by the coming Android SDK

Permission

Value Meaning
not_requested The permission sheet has not been shown
requested The permission sheet was shown and closed
granted, partial, denied Not reported on iOS. Used by the coming Android SDK, where Health Connect reports grants

Apple does not tell apps which read permissions the user granted. The SDK cannot tell a denied type from a type with no data, so on iOS the value stops at requested. A user who denied everything still shows requested, and simply sends no data.

Connection

Value Meaning
disconnected Not connected on this installation
connecting connect is in progress, or it returned pending_cleanup
connected Connected. The SDK syncs
disconnecting disconnect was accepted and Sonar is deleting the data. This stays until the app launches again or you call connect

Synchronization

Value Meaning
idle No run is active. Also shown while the phone is locked, since iOS hides Health data until the next unlock
syncing_recent Importing the last 30 days
syncing_historical Importing older history, back to the start of the history period
syncing_incremental Sending new data
temporarily_unavailable The last sync could not finish, for example because the network failed. The SDK tries again on its next sync

Recovery Action

recoveryAction tells your app what, if anything, the user or the app should do.

Value What to do
none Nothing
retry Nothing now. The SDK retries on its own
authenticate Call authenticate with a working token provider
connect_provider Offer to connect again. Shown after another installation took over, after the connection was removed, or when the user’s account holds the connection on another installation and this one needs the Health sheet to pick it up
contact_support Sonar refused data for a reason the SDK cannot fix. Send diagnostics
sign_out Call signOut, then authenticate
fix_configuration Fix the app setup: app ID, HealthKit capability, or usage description
request_permission Call connect again to show the Health permission sheet. On iOS, the user never answered it for some types. The other types keep syncing, and these start once allowed
open_settings Ask the user to allow Health access in the phone’s Settings. On iOS, Health is restricted on this phone, for example by Screen Time or device management
install_provider, update_provider Not used on iOS. Used by the coming Android SDK

On iOS, provider state uses every value except sign_out, fix_configuration, install_provider and update_provider. sign_out and fix_configuration come with errors.

Errors

Every rejected call rejects with a SonarSdkError:

typescript
class SonarSdkError extends Error {
  code: SonarSdkErrorCode;
  message: string;
  retryable: boolean;
  recoveryAction: RecoveryAction;
  provider: NativeProvider | null;
}

In Swift, SonarSdkError.code is an enum whose raw values are the codes below (.notConfigured is not_configured).

Code Retryable Recovery action When
not_configured No fix_configuration A call was made before configure, or historyDays is outside 30 to 1825
configuration_conflict No sign_out configure with a different app ID while a session exists
authentication_required No authenticate A call needs a session and there is none, or the token provider is missing
client_token_unavailable Yes retry Your token provider threw, or, in React Native, did not answer within 60 seconds
reauthorization_required No authenticate Sonar refused the client token, or the session ended and could not be renewed
user_deleted No authenticate Your backend deleted the user. The SDK has already cleared its state on this device
unsupported_provider No fix_configuration A provider other than apple_health on iOS, or a provider not enabled for your SDK app
provider_unavailable No none The device has no Apple Health
provider_install_required No install_provider Android only: Health Connect is not installed
provider_update_required No update_provider Android only: Health Connect needs an update
provider_configuration_required No fix_configuration The app lacks the HealthKit capability or the usage description
permission_denied No open_settings Android only: the user granted no Health Connect access
provider_not_connected No connect_provider sync or resync while Apple Health is not connected
temporarily_unavailable Yes retry Sonar could not be reached or could not answer. Try again later
platform_unsupported No none React Native only: a call on Android, before the package turns on Health Connect. signOut resolves and getState reports signed_out
unexpected No contact_support React Native only: the native error could not be read

A call rejects only when its own step fails. Problems during later background work show up in observeState, through synchronization and recoveryAction. Do not retry uploads yourself: when a sync fails, the SDK sends the same data again on its next sync.

Diagnostics

diagnostics() returns the SDK’s log, oldest line first: lifecycle calls, syncs, Sonar’s answers, and errors. It never holds health values. It is always on and keeps only the most recent lines.

sendDiagnostics() uploads the log to Sonar and returns a receiptId. Quote it when you contact support. setVerboseDiagnostics(true) also logs every Health read. Use it to investigate one device, not in a release build.