@adahealth/react-native-apple-healthkit v1.0.0
react-native-apple-healthkit
A React Native bridge module for interacting with Apple HealthKit data.
Notice
We are using this module for our app and thus need full control over it in the shortterm. It's forked from https://github.com/GregWilson/react-native-apple-healthkit and we're happy to contribute back to that.
Docs are outdated, because this module is now Promise based, to better align with the react-native ecosystem.
Table of Contents
- Getting Started
- Documentation
- Permissions
- Methods
- isAvailable
- initHealthKit
- getBiologicalSex
- getDateOfBirth
- getStepCount
getStepCountForTodaygetStepCountForDay- getDailyStepCountSamples
getMultiDayStepCounts- saveSteps
- getDistanceWalkingRunning
- getDistanceCycling
- getFlightsClimbed
- getLatestWeight
- getWeightSamples
- saveWeight
- getLatestHeight
- getHeightSamples
- saveHeight
- getLatestBmi
- saveBmi
- getLatestBodyFatPercentage
- getLatestLeanBodyMass
- getHeartRateSamples
- getBodyTemperatureSamples
- getBloodPressureSamples
- getRespiratoryRateSamples
- getBloodGlucoseSamples
- Examples
Getting started
Installation
Install the react-native-apple-healthkit package from npm:
npm install react-native-apple-healthkit --save
Xcode
- In XCode, in the project navigator, right click
Libraries
➜Add Files to [your project's name]
- Go to
node_modules
➜react-native-apple-healthkit
and addRCTAppleHealthKit.xcodeproj
- In XCode, in the project navigator, select your project. Add
libRCTAppleHealthKit.a
to your project'sBuild Phases
➜Link Binary With Libraries
- Click
RCTAppleHealthKit.xcodeproj
in the project navigator and go theBuild Settings
tab. Make sure 'All' is toggled on (instead of 'Basic'). In theSearch Paths
section, look forHeader Search Paths
and make sure it contains both$(SRCROOT)/../../react-native/React
and$(SRCROOT)/../../../React
- mark both asrecursive
. Enable HealthKit in your application's
Capabilities
Compile and run
Usage
Just require
the react-native-apple-healthkit
module and you're ready to go!
var AppleHealthKit = require('react-native-apple-healthkit');
...
let options = {
permissions: {
read: ["Height", "Weight", "StepCount", "DateOfBirth", "BodyMassIndex"],
write: ["Weight", "StepCount", "BodyMassIndex"]
}
};
AppleHealthKit.initHealthKit(options: Object, (err: Object, res: Object) => {
if(err) {
console.log("error initializing healthkit: ", err);
return;
}
// healthkit initialized...
});
When the module has been successfully initialized you can read and write HealthKit data
var AppleHealthKit = require('react-native-apple-healthkit');
var _ = require('lodash');
...
AppleHealthKit.getLatestWeight(null, (err: Object, weight: Object) => {
if(err){
console.log("error getting current weight: ", err);
return;
}
// use weight.value ...
});
...
let options = {value: 200};
AppleHealthKit.saveWeight(options: Object, (err: Object, res: Object) => {
if(err){
console.log("error saving weight to healthkit: ", err);
return;
}
// weight successfully saved
});
Documentation
Permissions
The available HealthKit permissions to use with initHealthKit
These permissions are exported as constants of the react-native-apple-healthkit
module.
import AppleHealthKit from 'react-native-apple-healthkit';
...
// get the available permissions from AppleHealthKit.Constants object
const PERMS = AppleHealthKit.Constants.Permissions;
// setup healthkit read/write permissions using PERMS
const healthKitOptions = {
permissions: {
read: [
PERMS.StepCount,
PERMS.Height,
],
write: [
PERMS.StepCount
],
}
};
...
Options
Methods
isAvailable
Check if HealthKit is available on the device.
AppleHealthKit.isAvailable((err: Object, available: boolean) => {
if(available){
// ...
}
});
initHealthKit
Initialize HealthKit. This will show the HealthKit permissions prompt for any read/write permissions set in the required options
object.
Due to Apple's privacy model if an app user has previously denied a specific permission then they can not be prompted again for that same permission. The app user would have to go into the Apple Health app and grant the permission to your react-native app under sources tab.
For any data that is read from HealthKit the status/error is the same for both. This privacy restriction results in having no knowledge of whether the permission was denied (make sure it's added to the permissions options object), or the data for the specific request was nil (ex. no steps recorded today).
For any data written to HealthKit an authorization error can be caught. If an authorization error occurs you can prompt the user to set the specific permission or add the permission to the options object if not present.
If new read/write permissions are added to the options object then the app user will see the HealthKit permissions prompt with the new permissions to allow.
initHealthKit
requires an options object with HealthKit permission settings
let options = {
permissions: {
read: ["Height", "Weight", "StepCount", "DateOfBirth", "BodyMassIndex"],
write: ["Weight", "StepCount", "BodyMassIndex"]
}
};
AppleHealthKit.initHealthKit(options: Object, (err: string, res: Object) => {
if(err) {
console.log("error initializing healthkit: ", err);
return;
}
// healthkit is initialized...
// now safe to read and write healthkit data...
});
getBiologicalSex
Get the biological sex (gender). If the BiologicalSex
read permission is missing or the user has denied it then the value will be unknown
. The possible values are:
Value | HKBiologicalSex |
---|---|
unknown | HKBiologicalSexNotSet |
male | HKBiologicalSexMale |
female | HKBiologicalSexFemale |
other | HKBiologicalSexOther |
AppleHealthKit.getBiologicalSex(null, (err: Object, res: Object) => {
if(this._handleHealthKitError(err, 'getBiologicalSex')){
return;
}
// res.value will be one of the values from the above table (Value column)
// use res.value ...
});
getDateOfBirth
Get the date of birth.
On success, the callback function will be provided with a res
object containing dob value: string
(ISO timestamp), and age: number
(age in years):
{
value: '1986-09-01T00:00:00.000-0400',
age: 29
}
AppleHealthKit.getDateOfBirth(null, (err: Object, res: Object) => {
if(this._handleHealthKitError(err, 'getDateOfBirth')){
return;
}
// use res.value ... (ex: '1986-09-01T12:20:30-04:00')
// use res.age ... (ex: 29)
});
getStepCount
Get the aggregated total steps for a specific day (starting and ending at midnight).
An optional options object may be provided containing date
field representing the selected day. If date
is not set or an options object is not provided then the current day will be used.
let d = new Date(2016,5,27);
let options = {
date: d.toISOString()
};
AppleHealthKit.getStepCount(options: Object, (err: Object, steps: Object) => {
if(this._handleHealthKitError(err, 'getStepCount')){
return;
}
// steps.value is the step count for day 'd'
});
getStepCountForToday
getStepCountForToday
removed - replaced by getStepCount
get the aggregated total steps for the current day starting and ending at midnight
AppleHealthKit.getStepCountForToday(null, (err: Object, steps: number) => {
if(this._handleHealthKitError(err, 'getStepCountForToday')){
return;
}
// use steps...
});
getStepCountForDay
getStepCountForDay
removed - replaced by getStepCount
get the the aggregated total steps for the day provided as date
in options object. the date
field expects an ISO date string as its value
let d = new Date(2016,5,27);
let options = {
date: d.toISOString()
};
AppleHealthKit.getStepCountForDay(options: Object, (err: Object, steps: number) => {
if(this._handleHealthKitError(err, 'getStepCountForDay')){
return;
}
// steps is the step count for day 'd'
});
getDailyStepCountSamples
Get the total steps per day over a specified date range.
getDailyStepCountSamples
accepts an options object containing required startDate: ISO8601Timestamp
and optional endDate: ISO8601Timestamp
. If endDate
is not provided it will default to the current time
let options = {
startDate: (new Date(2016,5,1)).toISOString() // required
endDate: (new Date()).toISOString() // optional; default now
};
The function will be called with an array of elements. Each element is an object containing value
, startDate
, and endDate
fields:
[
{ value: 8, startDate: '2016-07-09T00:00:00.000-0400', endDate: '2016-07-10T00:00:00.000-0400' },
{ value: 1923, startDate: '2016-07-08T00:00:00.000-0400', endDate: '2016-07-09T00:00:00.000-0400' },
{ value: 1802, startDate: '2016-07-07T00:00:00.000-0400', endDate: '2016-07-08T00:00:00.000-0400' },
...
]
AppleHealthKit.getDailyStepCountSamples(options: Object, (err: Object, res: Array<Object>) => {
if(this._handleHealthKitError(err, 'getDailyStepCountSamples')){
return;
}
// 'res' is array of {value: number, startDate: string, endDate: string} objects
// sorted ascending from startDate through endDate
for(let i=0; i<res.length; ++i){
let elem = res[i];
let stepCount = elem.value;
let day = elem.startDate;
// ...
}
});
getMultiDayStepCounts
getMultiDayStepCounts
removed - replaced by getDailyStepCountSamples
Get the total steps per day over a specified date range.
getMultiDayStepCounts
accepts an options object containing required startDate: ISO8601Timestamp
and optional endDate: ISO8601Timestamp
. if endDate
is not provided it will default to the current time
let options = {
startDate: (new Date(2016,5,1)).toISOString() // required
endDate: (new Date()).toISOString() // optional; default now
};
the function will be called with an array of elements res
containing date and step count information
AppleHealthKit.getMultiDayStepCounts(options: Object, (err: Object, res: Array<Array<string|number>>) => {
if(this._handleHealthKitError(err, 'getMultiDayStepCounts')){
return;
}
// 'res' is array of [ISOTimestamp: string, stepCount: number] arrays
// sorted ascending from startDate through endDate
for(let i=0; i<res.length; ++i){
let elem = res[i];
// elem[0] is ISOTimestamp : string
// elem[1] is step count : number
}
});
saveSteps
Save a step count sample.
A step count sample represents the number of steps during a specific period of time. A sample should be a precise as possible, with startDate and endDate representing the range of time the steps were taken in.
saveSteps
accepts an options object containing required value: number
, startDate: ISO8601Timestamp
, and endDate: ISO8601Timestamp
.
// startDate and endDate are 30 minutes apart.
// this means the step count value occured within those 30 minutes.
let options = {
value: 100,
startDate: (new Date(2016,6,2,6,0,0)).toISOString(),
endDate: (new Date(2016,6,2,6,30,0)).toISOString()
};
AppleHealthKit.saveSteps(options, (err, res) => {
if(this._handleHKError(err, 'saveSteps')){
return;
}
// step count sample successfully saved
});
getDistanceWalkingRunning
Get the total distance walking/running on a specific day.
getDistanceWalkingRunning
accepts an options object containing optional date: ISO8601Timestamp
and unit: string
. If date
is not provided it will default to the current time. unit
defaults to meter
.
let options = {
unit: 'mile', // optional; default 'meter'
date: (new Date(2016,5,1)).toISOString(), // optional; default now
};
AppleHealthKit.getDistanceWalkingRunning(options: Object, (err: Object, res: Object) => {
if(this._handleHKError(err, 'getDistanceWalkingRunning')){
return;
}
// use res.value ...
});
getDistanceCycling
Get the total distance cycling on a specific day.
getDistanceCycling
accepts an options object containing optional date: ISO8601Timestamp
and unit: string
. If date
is not provided it will default to the current time. unit
defaults to meter
let options = {
unit: 'meter', // optional; default 'meter'
date: (new Date(2016,5,1)).toISOString(), // optional; default now
};
AppleHealthKit.getDistanceCycling(options: Object, (err: Object, res: Object) => {
if(this._handleHKError(err, 'getDistanceCycling')){
return;
}
// use res.value ...
});
getFlightsClimbed
get the total flights climbed (1 flight is ~10ft of elevation) on a specific day.
getFlightsClimbed
accepts an options object containing optional date: ISO8601Timestamp
. if date
is not provided it will default to the current time.
let options = {
date: (new Date(2016,5,1)).toISOString(), // optional; default now
};
AppleHealthKit.getFlightsClimbed(options: Object, (err: Object, res: Object) => {
if(this._handleHKError(err, 'getFlightsClimbed')){
return;
}
// use res.value ...
});
getLatestWeight
Get the most recent weight sample.
On success, the callback function will be provided with a weight
object containing the weight value
, and the startDate
and endDate
of the weight sample. Note: startDate and endDate will be the same as weight samples are saved at a specific point in time.
{
value: 200,
startDate: '2016-07-08T12:00:00.000-0400',
endDate: '2016-07-08T12:00:00.000-0400'
}
AppleHealthKit.getLatestWeight(null, (err: string, weight: Object) => {
if(err){
console.log("error getting latest weight: ", err);
return;
}
// use weight.value, weight.startDate, etc ...
});
getWeightSamples
query for weight samples. the options object is used to setup a query to retrieve relevant samples.
let options = {
unit: 'pound', // optional; default 'pound'
startDate: (new Date(2016,4,27)).toISOString(), // required
endDate: (new Date()).toISOString(), // optional; default now
ascending: false, // optional; default false
limit:10, // optional; default no limit
};
AppleHealthKit.getWeightSamples(options, (err: Object, samples: Array<Object>) => {
if(this._handleHealthKitError(err, 'getWeightSamples')){
return;
}
// use samples ...
});
saveWeight
save a numeric weight value to HealthKit
saveWeight
accepts an options object containing a numeric weight value:
let options = {value: 200}
AppleHealthKit.saveWeight(options: Object, (err: Object, res: Object) => {
if(err){
console.log("error saving weight to healthkit: ", err);
return;
}
// weight successfully saved
});
getLatestHeight
Get the most recent height value.
On success, the callback function will be provided with a height
object containing the height value
, and the startDate
and endDate
of the height sample. Note: startDate and endDate will be the same as height samples are saved at a specific point in time.
{
value: 72,
startDate: '2016-07-08T12:00:00.000-0400',
endDate: '2016-07-08T12:00:00.000-0400'
}
AppleHealthKit.getLatestHeight(null, (err: string, height: Object) => {
if(err){
console.log("error getting latest height: ", err);
return;
}
// use height.value, height.startDate, etc ...
});
getHeightSamples
query for height samples. the options object is used to setup a query to retrieve relevant samples.
let options = {
unit: 'inch', // optional; default 'inch'
startDate: (new Date(2016,4,27)).toISOString(), // required
endDate: (new Date()).toISOString(), // optional; default now
ascending: false, // optional; default false
limit:10, // optional; default no limit
};
the callback function will be called with a samples
array containing objects with value, startDate, and endDate fields
// samples is array of objects
[
{value: 74.02, startDate:'2016-06-29T17:55:00.000-0400', endDate:'2016-06-29T17:55:00.000-0400'},
{value: 74, startDate:'2016-03-12T13:22:00.000-0400', endDate:'2016-03-12T13:22:00.000-0400'},
...
]
example usage
AppleHealthKit.getHeightSamples(options, (err: Object, samples: Array<Object>) => {
if(this._handleHealthKitError(err, 'getHeightSamples')){
return;
}
// use samples ...
});
saveHeight
save a numeric height value to HealthKit
saveHeight
accepts an options object containing a numeric height value:
let options = {value: 200}
AppleHealthKit.saveHeight(options: Object, (err: Object, res: Object) => {
if(this._handleHealthKitError(err, 'saveHeight')){
return;
}
// height successfully saved
});
getLatestBmi
Get the most recent BMI sample.
On success, the callback function will be provided with a bmi
object containing the BMI value
, and the startDate
and endDate
of the sample. Note: startDate and endDate will be the same as bmi samples are saved at a specific point in time.
{
value: 27.2,
startDate: '2016-07-08T12:00:00.000-0400',
endDate: '2016-07-08T12:00:00.000-0400'
}
AppleHealthKit.getLatestBmi(null, (err: string, bmi: Object) => {
if(err){
console.log("error getting latest bmi data: ", err);
return;
}
let d = bmi.startDate
let val = bmi.value;
// ...
});
saveBmi
save a numeric BMI value to HealthKit
saveBmi
accepts an options object containing a numeric BMI value:
let options = {value: 27.2}
AppleHealthKit.saveBmi(options: Object, (err: Object, res: Object) => {
if(this._handleHealthKitError(err, 'saveBmi')){
return;
}
// BMI successfully saved
});
getLatestBodyFatPercentage
Get the most recent body fat percentage. The percentage value is a number between 0 and 100.
On success, the callback function will be provided with a bodyFatPercentage
object containing the body fat percentage value
, and the startDate
and endDate
of the sample. Note: startDate and endDate will be the same as bodyFatPercentage samples are saved at a specific point in time.
{
value: 20,
startDate: '2016-07-08T12:00:00.000-0400',
endDate: '2016-07-08T12:00:00.000-0400'
}
AppleHealthKit.getLatestBodyFatPercentage(null, (err: Object, bodyFatPercentage: Object) => {
if(this._handleHealthKitError(err, 'getLatestBodyFatPercentage')){
return;
}
// use bodyFatPercentage.value, bodyFatPercentage.startDate, etc ...
});
getLatestLeanBodyMass
Get the most recent lean body mass. The value is a number representing the weight in pounds (lbs)
On success, the callback function will be provided with a leanBodyMass
object containing the leanBodyMass value
, and the startDate
and endDate
of the sample. Note: startDate and endDate will be the same as leanBodyMass samples are saved at a specific point in time.
{
value: 176,
startDate: '2016-07-08T12:00:00.000-0400',
endDate: '2016-07-08T12:00:00.000-0400'
}
AppleHealthKit.getLatestLeanBodyMass(null, (err: Object, leanBodyMass: Object) => {
if(this._handleHealthKitError(err, 'getLatestLeanBodyMass')){
return;
}
// use leanBodyMass.value, leanBodyMass.startDate, etc ...
});
getHeartRateSamples
query for heart rate samples. the options object is used to setup a query to retrieve relevant samples.
let options = {
unit: 'bpm', // optional; default 'bpm'
startDate: (new Date(2016,4,27)).toISOString(), // required
endDate: (new Date()).toISOString(), // optional; default now
ascending: false, // optional; default false
limit:10, // optional; default no limit
};
the callback function will be called with a samples
array containing objects with value, startDate, and endDate fields
example usage
AppleHealthKit.getHeartRateSamples(options, (err: Object, samples: Array<Object>) => {
if(this._handleHealthKitError(err, 'getHeartRateSamples')){
return;
}
// use samples ...
});
getBodyTemperatureSamples
query for body temperature samples. the options object is used to setup a query to retrieve relevant samples.
let options = {
unit: 'celsius', // optional; default 'celsius'
startDate: (new Date(2016,4,27)).toISOString(), // required
endDate: (new Date()).toISOString(), // optional; default now
ascending: false, // optional; default false
limit:10, // optional; default no limit
};
available units are: 'fahrenheit'
, 'celsius'
.
the callback function will be called with a samples
array containing objects with value, startDate, and endDate fields.
example usage
AppleHealthKit.getBodyTemperatureSamples(options, (err: Object, samples: Array<Object>) => {
if(this._handleHealthKitError(err, 'getBodyTemperatureSamples')){
return;
}
// use samples ...
});
getBloodPressureSamples
query for blood pressure samples. the options object is used to setup a query to retrieve relevant samples.
let options = {
unit: 'mmhg', // optional; default 'mmhg'
startDate: (new Date(2016,4,27)).toISOString(), // required
endDate: (new Date()).toISOString(), // optional; default now
ascending: false, // optional; default false
limit:10, // optional; default no limit
};
the callback function will be called with a samples
array containing objects with bloodPressureSystolicValue, bloodPressureDiastolicValue, startDate, and endDate fields
// samples is array of objects
[
{bloodPressureSystolicValue: 120, bloodPressureDiastolicValue: 81, startDate:'2016-06-29T17:55:00.000-0400', endDate:'2016-06-29T17:55:00.000-0400'},
{bloodPressureSystolicValue: 119, bloodPressureDiastolicValue: 77, startDate:'2016-03-12T13:22:00.000-0400', endDate:'2016-03-12T13:22:00.000-0400'},
...
]
example usage
AppleHealthKit.getBloodPressureSamples(options, (err: Object, samples: Array<Object>) => {
if(this._handleHealthKitError(err, 'getBloodPressureSamples')){
return;
}
// use samples ...
});
getRespiratoryRateSamples
query for respiratory rate samples. the options object is used to setup a query to retrieve relevant samples.
let options = {
unit: 'bpm', // optional; default 'bpm'
startDate: (new Date(2016,4,27)).toISOString(), // required
endDate: (new Date()).toISOString(), // optional; default now
ascending: false, // optional; default false
limit:10, // optional; default no limit
};
the callback function will be called with a samples
array containing objects with value, startDate, and endDate fields
example usage
AppleHealthKit.getRespiratoryRateSamples(options, (err: Object, samples: Array<Object>) => {
if(this._handleHealthKitError(err, 'getRespiratoryRateSamples')){
return;
}
// use samples ...
});
getBloodGlucoseSamples
query for blood glucose samples. the options object is used to setup a query to retrieve relevant samples.
let options = {
unit: 'mmolPerL', // optional; default 'mmolPerL'
startDate: (new Date(2016,4,27)).toISOString(), // required
endDate: (new Date()).toISOString(), // optional; default now
ascending: false, // optional; default false
limit:10, // optional; default no limit
};
available units are: 'mmolPerL'
, 'mgPerdL'
.
the callback function will be called with a samples
array containing objects with value, startDate, and endDate fields
example usage
AppleHealthKit.getBloodGlucoseSamples(options, (err: Object, samples: Array<Object>) => {
if(this._handleHealthKitError(err, 'getBloodGlucoseSamples')){
return;
}
// use samples ...
});
Examples
StepsDemo
BodyMeasurements
8 years ago