Mobile SDK

React Native

Current React Native SDK Version: 2.5.8

React Native Package can be found here

Spike ReactNative SDK is a library on top of Apple HealthKit and Android HealthConnect that

  1. helps with the extraction of data.
  2. pushes data to SpikeAPI and delivers standardized data.

Requirements

  • iOS 13.0+
  • Android 9.0 +

iOS Signing & Capabilities

To add HealthKit support to your application's Capabilities.

  • Open the iOS/ folder of your project in Xcode
  • Select the project name in the left sidebar
  • Open Signing & Capabilities section
  • In the main view select '+ Capability' and double click HealthKit
  • Allow Background Delivery, if needed.
Document image


More details you can find here.

Info.plist

Add Health Kit permissions descriptions to your Info.plist file.

Info.plist


Android Setup

First of all you have to add the required health permissions to a resource file. You can reuse an existing one or create a new one. That allows you to fully utilise this SDK and to read the necessary data from apps that integrate with HealthConnect. Please refer to this guide to understand the specific permissions needed.

XML


Then reference the permissions to your AndroidManifest.xml file in the activity that will call for health permissions.

AndroidManifest


As well as that you have to add intent filter to your activity definition so that you can request the permissions at runtime.

AndroidManifest


Installation

Install the react-native-spike-sdk package from npm

yarn add react-native-spike-sdk

Use pod install and pod update commands from ios/ folder of your app to install/update pods afterward.

Android

To add the SDK to your Android project, you have to add the following to your project's build.gradle file in the repositories block.

JSON


Configuration

1. Import Spike to your project.

import Spike from 'react-native-spike-sdk';

2. Add Spike initialization code to ios/<Project Name>/AppDelegate.mm file inside application:didFinishLaunchingWithOptions: method.

AppDelegate.mm


3. To set up the Spike SDK create SpikeConnection instance with the SpikeConnectionConfig object. From the 2.1.x version Spike SDK automatically manages connection persistence and restores connection if finds one with the same appId, authToken, and customerEndUserId. With each new connection creating call callbackUrl and env could be overridden. Provide SpikeLogger implementation to handle connection logs.

ReactNative


Permissions

Provide permissions to access iOS HealthKit and Android HealthConnect data. Spike SDK methods will check required permissions and request them if needed. Permission dialog may not be shown according to platform permissions rules.



Getting and using data

There are two ways to get Spike data: to your webhook or directly in your app. Extract data methods require SpikeExtractConfig object, where date range can be provided optionally. By providing a range greater than one day sample array of the result object will be empty. The maximum permitted date range for iOS is 90 days, while for Android it's 30 days.

JS


Extracting data by time range

Params from and to enable the extraction of local device data for the given time range. The maximum allowed single-query time interval is 7 days. If required, data of any longer time period can be accessed by iterating multiple queries of 7 days.

JS


Sending data to webhook

Extracts local device data for the given time range and sends it as a webhook notification to the customer’s backend.

Ensure callbackUrl was provided to SpikeConnection, otherwise, you will get SpikeCallbackURLNotProvidedException error. The method will return the job information object.

JS


Background Delivery (iOS Only)

Background delivery enables asynchronous data delivery to the customer backend through webhooks. It enables data updates to be sent to the backend even when the application is hidden or closed. Background delivery is only supported on iOS devices at the moment. Background deliveries will send whole-day data to the webhook.

Note: The Healthkit has its own data delivery prioritization logic since iOS manages the background delivery, and the update frequency is influenced by several factors, including app usage frequency, the iOS version, battery status, and network connectivity. We suggest invoking the 'extractAndPostData' function when the app is launched. For instance, you can extract data from the past 7 days and synchronize it, ensuring that users always have access to the most up-to-date information;

Configure for background deliveries

Under your project Signing & Capabilities section enable Background Delivery for HealthKit. Call Spike configure methods on each app start for triggering background delivery tasks. Add Spike initialization code to ios/<Project Name>/AppDelegate.mm file inside application:didFinishLaunchingWithOptions: method.

AppDelegate.mm


Register connection for background deliveries

Ensure callbackUrl was provided to SpikeConnection, otherwise, you will get SpikeCallbackURLNotProvidedException error. Provide required Spike Data types to enableBackgroundDelivery method, it could be called after the connection is created.

JS

  • If dataTypes is not empty, then a daemon task is started which will listen for data updates coming from the platform and send them via webhooks in the background; the operation is not compound and each method call will override the enabled background data types list;
  • If dataTypes parameter is empty or null, then background data delivery is stopped for this connection if it was enabled;

You can check if the connection has active background delivery listeners. If background delivery is not enabled, an empty set is returned.

const dataTypes = await conn.getBackgroundDeliveryDataTypes();

Logging

Internally, the React Native SDK supports logging on various levels to assist with troubleshooting. However, to avoid imposing additional third-party dependencies on library users, the SDK expects a concrete logging implementation to be provided externally. This can be done by implementing the SpikeLogger class and providing it when creating or unpacking a connection.

Below is an example of how to implement a simple console logger.

JS


Spike SDK provides background delivery process logs. This can be done by implementing the SpikeBackgroundDeliveriesLogger class and providing it through the connection's setListener method. Below is an example of how to implement a simple console logger.

RN


Publishing application on the Play Store

The SpikeSDK for Android devices integrates with Health Connect for data retrieval. Before publishing the application to the Play Store, application owners are required to complete the Developer Declaration Form available at the following link: Developer Declaration Form

Please make sure that all types are selected from permissions section as shown here

Data types

The following table shows the data types that can be read from HealthConnect API and the permissions that are required to read them.

Spike Data Type

HealthConnect permission

SpikeDataTypes.HEART_RATE

android.permission.health.READ_HEART_RATE

android.permission.health.READ_HEART_RATE_VARIABILITY

android.permission.health.READ_RESTING_HEART_RATE

SpikeDataTypes.DISTANCE

android.permission.health.READ_DISTANCE

SpikeDataTypes.ACTIVITIES_STREAM

android.permission.health.READ_EXERCISE

android.permission.health.READ_STEPS

android.permission.health.READ_DISTANCE

android.permission.health.READ_TOTAL_CALORIES_BURNED

android.permission.health.READ_HEART_RATE

android.permission.health.READ_SPEED

android.permission.health.READ_ELEVATION_GAINED

android.permission.health.READ_POWER

android.permission.health.READ_HEART_RATE_VARIABILITY

SpikeDataTypes.ACTIVITIES_SUMMARY

android.permission.health.READ_STEPS

android.permission.health.READ_ACTIVE_CALORIES_BURNED

android.permission.health.READ_TOTAL_CALORIES_BURNED

android.permission.health.READ_DISTANCE

android.permission.health.READ_ELEVATION_GAINED

android.permission.health.READ_FLOORS_CLIMBED

android.permission.health.READ_HEART_RATE

android.permission.health.READ_RESTING_HEART_RATE

android.permission.health.READ_BASAL_METABOLIC_RATE

SpikeDataTypes.BREATHING

android.permission.health.READ_RESPIRATORY_RATE

SpikeDataTypes.CALORIES

android.permission.health.READ_TOTAL_CALORIES_BURNED

android.permission.health.READ_ACTIVE_CALORIES_BURNED

SpikeDataTypes.GLUCOSE

android.permission.health.READ_BLOOD_GLUCOSE

SpikeDataTypes.OXYGEN_SATURATION

android.permission.health.READ_OXYGEN_SATURATION

SpikeDataTypes.SLEEP

android.permission.health.READ_SLEEP

android.permission.health.READ_HEART_RATE

android.permission.health.READ_HEART_RATE_VARIABILITY

SpikeDataTypes.STEPS

android.permission.health.READ_STEPS

SpikeDataTypes.BODY

android.permission.health.READ_WEIGHT

android.permission.health.READ_HEIGHT

android.permission.health.READ_BODY_FAT

android.permission.health.READ_BONE_MASS

android.permission.health.READ_BLOOD_PRESSURE

android.permission.health.READ_BODY_TEMPERATURE

Classes

Spike

Class

Method

Description

Spike

createConnection

Creates a new SpikeConnection instance with the given user details. Parameters: config (SpikeConnectionConfig), logger? (SpikeLogger) . Returns: An instance of the SpikeConnection class (SpikeConnection).

Spike

getBackgroundConnections

Returns all connections that are configured to deliver data in the background. Returns: An array of SpikeConnection instances with callbackUrl (Array<SpikeConnection>).

Spike

ensurePermissionsAreGranted

Verifies that platform-specific permissions corresponding to the Spike data types provided are granted. In the event that some permissions are not granted, a platform-specific permissions dialogue will be presented to the end-user. This method should only be invoked from a UI component. Parameters: permissions (Array<SpikeDataType>)

Spike

isPackageInstalled

Check if Health Connect is installed on a device.

SpikeConnection

Class

Method

Description

iOS

Android

SpikeConnection

getAppId

Retrieves the unique Spike application identifier.

Returns: appId (string)

Yes

Yes

SpikeConnection

getSpikeEndUserId

Retrieves the unique identifier assigned to the end-user by Spike.

Returns: spikeEndUserId (string)

Yes

Yes

SpikeConnection

getCustomerEndUserId

Retrieves the unique identifier assigned to the end-user by the customer.

Returns: customerEndUserId (string)

Yes

Yes

SpikeConnection

getCallbackUrl

Returns the URL that will receive webhook notifications. Returns: callbackUrl (string)

Yes

Yes

SpikeConnection

close

Terminates any ongoing connections with Spike’s backend servers, clears any caches, and removes provided user details and tokens from the memory. Once the connection is closed, it cannot be used, and any method other than close() will throw a SpikeConnectionIsClosed exception.

Yes

Yes

SpikeConnection

extractData

Extracts local device data for the current date in the end-user’s time zone. Optionally time range can be provided. *On iOS, the maximum allowed single-query time interval is 90 days. If required, data of any longer time period can be accessed by iterating multiple queries of 90 days. *On Android the earliest date data can be requested is 30 days before permission was given to the user's app to read from HealthConnect. There is no limit on how many days in total. Parameters: config (SpikeExtractConfig) Returns: An instance of SpikeData. The concrete type will depend on the data type requested

Yes

Yes

SpikeConnection

extractAndPostData

Extracts local device data for the current date in the local user time zone and sends it as a webhook notification to the customer’s backend. Optionally time range can be provided.

*On iOS, the maximum allowed single-query time interval is 90 days. If required, data of any longer time period can be accessed by iterating multiple queries of 90 days.

*On Android the earliest date data can be requested is 30 days before permission was given to the user's app to read from HealthConnect. There is no limit on how many days in total.

Parameters: config (SpikeExtractConfig)

Yes

Yes

SpikeConnection

manageHealthConnect

Opens your device's HealthConnect menu, where you can switch on and off data access for the app as well as delete data.

No

Yes

SpikeConnection

checkPermissionsGranted

Initiates a check on whether all health permissions have been granted to ensure the proper functioning of the SDK

No

Yes

SpikeConnection

getHealthConnectAvailability

Provides information on whether HealthConnect is available on the device.

No

Yes

SpikeConnection

revokeAllPermissions

Revokes all granted health permissions for the application.

No

Yes

SpikeConnection

requestHealthPermissions

Requests all the supported health read permissions from HealthConnect.

No

Yes

SpikeLogger

Abstract class allows to receive notifications from the SDK's processes.

Class

Method

Description

iOS

Android

SpikeLogger

isDebugEnabled

Manages is Debug level logging enabled. Returns: are Debug level logs enabled (boolean)

yes

yes

SpikeLogger

isInfoEnabled

Manages is Info level logging enabled. Returns: are Info level logs enabled (boolean)

yes

yes

SpikeLogger

isErrorEnabled

Manages is Error level logging enabled. Returns: are Error level logs enabled (boolean)

yes

yes

SpikeLogger

debug

Invoked on Spike SKD Debug log events. Parameters: connection (), message (string)

yes

yes

SpikeLogger

info

Invoked on Spike SKD Info log events. Parameters: connection (), message (string)

yes

yes

SpikeLogger

error

Invoked on Spike SKD Error log events. Parameters: connection (), message (string)

yes

yes

SpikeBackgroundDeliveriesLogger

Abstract class allows to receive notifications from the background data delivery process.

Class

Method

Description

iOS

Android

SpikeBackgroundDeliveriesLogger

onBackgroundLog

Invoked on background delivery events. Parameters: log (string)

yes

no

SpikeConnectionConfig

Type required to create Spike connection instance.

Type

Property

Type

Description

iOS

Android

SpikeConnectionConfig

appId

string

The unique Spike application identifier

yes

yes

SpikeConnectionConfig

authToken

string

The unique identifier assigned to the end-user by Spike.

yes

yes

SpikeConnectionConfig

customerEndUserId

string

the unique identifier assigned to the end-user by the customer.

yes

yes

SpikeConnectionConfig

callbackUrl

string

URL that will receive webhook notifications

yes

yes

SpikeConnectionConfig

env



Spike environment

yes

yes

SpikeExtractConfig

Type required to extract data.

Type

Property

Type

Description

iOS

Android

SpikeExtractConfig

dataType



The Spike data type to make extraction for.

yes

yes

SpikeExtractConfig

from

Date (optional)

Extraction time range start date. *Required if to property passed.

yes

yes

SpikeExtractConfig

to

Date (optional)

Extraction time range end date. *Required if from property passed.

yes

yes

Errors and Exceptions

SpikeException

The abstract parent of all concrete exceptions.

SpikeConnectionIsClosedException

Thrown if any method is invoked on SpikeConnection or one of its subclasses after the connection has been closed.

SpikeInvalidCredentialsException

Thrown if the credentials provided are not recognized, i.e. are invalid or expired.

SpikeInvalidDateRangeException

Thrown if the duration exceeds the allowed maximum or if the ‘from’ date is greater than the ‘to’ date. The message will contain a specific cause description.

SpikeInvalidCallbackUrlException

Thrown if the callback URL is not a valid URL, does not have HTTPS schema, or is not a sub-URL of the main callback URL configured for the application. The exception message will contain a specific reason.

SpikePermissionsNotGrantedException

Thrown when Spike SDK is unable to access the data due to permissions not being granted.

SpikeServerException

Whenever any operation with the Spike backend fails and the error does not fall into any of the above exceptions. The exception cause will contain the underlying error.

SpikeCallbackURLNotProvidedException

Thrown when a method which requires callback url is called, but callback url is not set for current connection.