Skip to main content

Usage: Sync health data automatically

Sync Apple Health data automatically on background and with every app launch.

You can sync health data every time the user opens your app (continuous upload) and/or every hour while the app is closed in the background (background sync).

tip

It is recommended to combine continuous upload and background sync for a better experience.

Background sync

AHRookBackgroundSync is a preconfigured component that allows to your app to sync health data while your app is in background until 14 days into the past. To enable this behaviour call enableBackground providing:

  void enableBackGround() async {
try {
AHRookBackgroundSync.enableBackground(
enableNativeLogs: isDebug,
clientUUID: Secrets.clientUUID,
secretKey: Secrets.secretKey,
environment: rookEnvironment,
);

// Success. You will start to notice that data is syncing.
} catch (exception) {
// Error
}
}
info

Please note that for security, iOS devices encrypt the HealthKit storage when users lock their devices. As a result, apps may not be able to read data from Apple Health when it runs in the background. Please refer to the official apple documentation for more information.

danger

Before calling enableBackground verify that your app has ALL permissions (SLEEP, PHYSICAL, BODY) granted and a user id is configured.

Background errors

When an error occurs in the Background Sync component, it can be listened by listening to the AHRookHelpers.backgroundErrorsUpdates stream:

  // 1.- Create a stream subscription
StreamSubscription<Exception>? streamSubscription;

// 2.- Listen to stream
streamSubscription = AHRookHelpers.backgroundErrorsUpdates.listen((backgroundError) {
// Process error
});

// 3.- Stop listening to the stream
streamSubscription?.cancel();

Continuous upload

AHRookContinuousUpload is a preconfigured component that allows to your app to sync health data every time a user opens the app. To enable this behaviour call enableContinuousUpload providing:

void enableContinuousUpload() async {
try {
AHRookContinuousUpload.enableContinuousUpload(
enableNativeLogs: isDebug,
clientUUID: Secrets.clientUUID,
secretKey: Secrets.secretKey,
environment: rookEnvironment,
);

// Success. You will start to notice that data is syncing (try restarting the app if this doesn't happen).
} catch (exception) {
// Error
}
}
danger

Before calling enableContinuousUpload verify that your app has ALL permissions (SLEEP, PHYSICAL, BODY) granted and a user id is configured then, the automatic sync will happen the next time the app is launched.