lucaspbordignon / rn-apple-healthkit Goto Github PK
View Code? Open in Web Editor NEWA React Native package for interacting with Apple HealthKit
Home Page: https://www.npmjs.com/package/react-native-health
License: MIT License
A React Native package for interacting with Apple HealthKit
Home Page: https://www.npmjs.com/package/react-native-health
License: MIT License
Is there anyway to tell the difference between user inputted step data vs phone sensor data / watch data?
I currently have a sort of work around but then I am unable to tell the difference between watch step data and user inputted steps.
I use a react-native-pedometer and get the difference between health kit steps and the pedometer steps. The pedometer only returns step data recorded by the phone's sensor.
Thanks.
after installing the library and calling AppleHealthKit.initHealthKit
I get the following error:
When I inspect the AppleHealthKit
imported object, there is just "constants" and "permissions" properties, no methods.
Hi Terillo,
I am new to React Native, I have npm installed and link the package.
I put this code in render
let options = { permissions: { read: ['Height', 'Weight', 'StepCount', 'DateOfBirth', 'BodyMassIndex'], write: ['Weight', 'StepCount', 'BodyMassIndex'] } } AppleHealthKit.isAvailable((err: Object, available: boolean) => { if (err) { console.log('error initializing Healthkit: ', err) return } // Healthkit is available })
But this showed up
Please let me know if there is anything I should pay attention to.
I followed the manual install directions exactly and when I build the project I am receiving this error.
the line is: #import <React/RCTBridgeModule.h>
line 12 of RCTAppleHealthKit.h
"react": "15.3.2",
"react-native": "0.34.1",
"rn-apple-healthkit": "^0.6.3",
I search in many places where the code to put to work but I can't find
Does this plugin also retrieve background data?
Does initStepCountObserver call on the background fetch as well
I'm building application that want to show user step in realtime but listener take too long to invoke.
Is it possible to show healthkit user step in realtime ?
this is my code
async componentDidmount() {
AppleHealthKit.initHealthKit(HKOPTIONS, (err, res) => {
if (err) {
console.log('error initializing Healthkit: ', err);
return;
}
AppleHealthKit.setObserver({ type: 'Walking' });
NativeAppEventEmitter.addListener('observer', () => console.log('fetch new data'));
});
}
I follow the setting and code with rn-apple-healthkit's document
However I got a strange mistake !!
Anyone have the answer?
`import React, { Component } from 'react';
import {
ScrollView,
Navigator,
View,
NativeAppEventEmitter,
} from 'react-native';
import axios from 'axios';
import AppleHealthKit from 'rn-apple-healthkit';
import AlbumDetail from './AlbumDetail';
const d = new Date();
const PERMS = AppleHealthKit.Constants.Permissions;
const HKOPTIONS = {
permissions: {
read: [
PERMS.StepCount,
PERMS.Height,
PERMS.Weight,
PERMS.DateOfBirth,
PERMS.BodyMassIndex,
],
write: [
PERMS.StepCount,
PERMS.Weight,
PERMS.BodyMassIndex,
],
},
date: d.toISOString()
};
AppleHealthKit.initHealthKit(HKOPTIONS, (err, res) => {
if (err) {
console.log('HealthkitInitError: ', err);
return;
}
console.log('HealthkitInitSucess');
AppleHealthKit.initStepCountObserver({}, () => {});
this.sub = NativeAppEventEmitter.addListener(
'change:steps',
(event) => {
// mistake is here!!!
this._fetchStepCountData();
console.log(event);
}
);
});
// StepCounter Example
AppleHealthKit.getStepCount(HKOPTIONS, (error, results) => {
if (error) {
console.log('getStepCountError: ', error);
return;
}
console.log(results);
});
class albumList extends Component {
state = { albums: [] };
componentWillMount() {
axios.get('https://rallycoding.herokuapp.com/api/music_albums')
.then(response => this.setState({ albums: response.data }))
.then(response => console.log(response));
}
componentDidMount() {
console.log(this.state.albums);
}
// when the component where the listener was added unmounts, call the 'remove' method of the subscription object.
componentWillUnmount() {
this.sub.remove();
};
renderAlbums() {
return this.state.albums.map(album =>
);
}
render() {
return (
{this.renderAlbums()}
);
}
}
export default albumList;`
Unable to read body fat percentage even though there is a method in doc ==> AppleHealthKit.getLatestBodyFatPercentage
.
Am getting below error
{"message":"error getting latest body fat percentageError Domain=com.apple.healthkit Code=5 \"Authorization not determined\" UserInfo={NSLocalizedDescription=Authorization not determined}"}
Currently this library won't work for anyone who has an app that has been detached from Expo (See #17), and possible anyone that uses CRNA. It'd be great if CocoaPods could be added. π
Hello, thanks for the great package!
We are using it in our app to import Apple Health data and aggregate it with blood pressure data users can input in our app as well.
When the permission is granted for us to read Apple Health data, the data I am requesting is successfully communicated to our app, where we can work with it.
But if I add another value in Apple Health after this and call AppleHealthkit.getBloodPressureSamples again, no new data is found and no error is caught.
Is this expected behaviour?
I hope this is enough to understand the problem, otherwise I can post some code as well.
I tried running it on the simulator as well as a real device, the initHealthKit
always returns no err
and res = 1
in the callback function so there is no way to know if the user actually gave HealthKit permissions or not.
I am building an app based on activeEnergy, but as I understand it, it's only available if you are using an apple watch (I am guessing fitbit as well). Is it possible to detect this? I want to default back to stepcount for users without an apple watch.
EDIT - I'm really confused. The file is in the directory /Users/adamhanna/Desktop/goLang/src/personal/rise/rise/node_modules/react-native/React/Base
, when I add that exact directory to my headers search path, it still errors. WTH?!
I installed the project automatically with yarn and react-native link rn-apple-healthkit but I'm still getting this error. See the error and my header search paths in the image, below. I'm at my wits end, any help would be appreciated. Thx
I see some of the methods have a start and end date in the options object that is provided, but the saveWeight only takes the value without dates.
Am I missing something or does this mean you can only save the current day's weight?
//MindfulSession
let MindFullSessionOptions = {
startDate: (new Date(2019,1,1)).toISOString(),
endDate: (new Date()).toISOString(),
};
AppleHealthKit.saveMindfulSession(MindFullSessionOptions, (err, res) => {
if (err) {
return
}
console.log('Mindful session saved')
});
I am working on this. For me success console won't display. I don't know whether any settings in the HealthKit needs to change. Please can anybody Suggest me on this.
Hi.
I just want to ask if you have a plan to make this to support new Health Records API?
Thanks
Is there a way to get any subscriber for heart rate as well , similar to step count ?? Like i need to get intimated whenever there is a change in the heart rate value in health kit .
Thanks for the writing the library.
However, I notice that there're only limited property to get samples.
How can I get samples for Water, ...etc
Thanks
Chris Chang
Hi, import
causes syntax error in testing via Jest. Do you have any idea to solve?
$ react-native init <ProjectName>
$ cd <ProjectName>
$ yarn test
yarn run v1.5.1
$ jest
PASS __tests__/App.js
β renders correctly (105ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.506s
Ran all test suites.
β¨ Done in 1.05s.
$ yarn add rn-apple-healthkit
diff --git a/App.js b/App.js
index dd1d45a..74f4f28 100644
--- a/App.js
+++ b/App.js
@@ -11,6 +11,7 @@ import {
Text,
View
} from 'react-native';
+import AppleHealthKit from 'rn-apple-healthkit';
$ yarn test
yarn run v1.5.1
$ jest
FAIL __tests__/App.js
β Test suite failed to run
/Users/takafumi/rn-apple-healthkit/appleHealthKit/node_modules/rn-apple-healthkit/index.js:5
import { Permissions } from './Constants/Permissions'
^^^^^^
SyntaxError: Unexpected token import
> 1 | /**
2 | * Sample React Native App
3 | * https://github.com/facebook/react-native
4 | * @flow
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:316:17)
at Object.<anonymous> (App.js:1:791)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 0.726s, estimated 6s
Ran all test suites.
error An unexpected error occurred: "Command failed.
Exit code: 1
Command: sh
Arguments: -c jest
Directory: /Users/takafumi/rn-apple-healthkit/appleHealthKit
Output:
".
info If you think this is a bug, please open a bug report with the information provided in "/Users/takafumi/rn-apple-healthkit/appleHealthKit/yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
$ sw_vers
ProductName: Mac OS X
ProductVersion: 10.13.3
BuildVersion: 17D102
$ node --version
v9.8.0
$ yarn --version
1.5.1
$ react-native --version
react-native-cli: 2.0.1
react-native: 0.54.2
Any way to map in items like Body Temperature added by a Thermo thermometer?
Hey all! I'm new to JavaScript/RN development, but I wanted to try my hand at making a small health app using data from Apple HealthKit.
I started a new project using create-react-native-app, installed rn-apple-healthkit, and linked it per README.md's instructions. However, when I import rn-apple-healthkit and run the sample code in my component, I get a TypeError. Again, I'm still pretty new to RN, so it might be that I just don't understand how the module is meant to interact with RN components. Any tips?
Here's what I'm running:
import React, { Component } from 'react';
import { View } from 'react-native';
import AppleHealthKit from 'rn-apple-healthkit';
export default class Health extends Component{
state = { available:false };
render(){
let options = { permissions: {
read: ['Height', 'Weight', 'StepCount', 'DateOfBirth', 'BodyMassIndex'],
write: ['Weight', 'StepCount', 'BodyMassIndex'] } };
AppleHealthKit.initHealthKit(options, (err,results) => {
if (err){
console.log('Error initializing Healthkit:', err)
return;
}
else {
AppleHealthKit.isAvailable((err,available) => {
if (err) {
console.log('Error initializing Healthkit:', err);
return;
}
else {
this.setState({ available:available })
}
})
}
})
return(
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
{(this.state.available ? 'Yes!': 'No!')}
</View>
)
}
}
Thanks in advance!
Is there any method to find Cholesterol ?
Is there a way to get more data types from the GetSamples
method? Specifically I am looking to get Active Calories, which currently is not available. The main motivation for wanting this is being able to access the isTracked
property.
Side note: The data types for the getSamples
method are not very clear. For example, the Running
type is for "Distance Walking/Running" but Running
suggests it is just for running. Similarly, Walking
is steps, which come from walking as well as running.
hello
i am use rn-apple-healthkit,system Prompt οΌ
_rnAppleHealthkit2.default.getBiologicalSex is not a function. (In '_rnAppleHealthkit2.default.getBiologicalSex', '_rnAppleHealthkit2.default.getBiologicalSex' is undefined)
componentDidMount
index.ios.js:43:40
measureLifeCyclePerf
ReactNativeStack-dev.js:1610:15
<unknown>
ReactNativeStack-dev.js:1657:33
notifyAll
ReactNativeStack-dev.js:2121:107
close
ReactNativeStack-dev.js:2138:8
closeAll
ReactNativeStack-dev.js:1412:101
perform
ReactNativeStack-dev.js:1388:52
batchedMountComponentIntoNode
ReactNativeStack-dev.js:2004:24
perform
ReactNativeStack-dev.js:1382:99
renderComponent
ReactNativeStack-dev.js:2032:45
renderApplication
renderApplication.js:34:4
runApplication
AppRegistry.js:191:26
__callFunction
MessageQueue.js:306:47
<unknown>
MessageQueue.js:108:26
__guard
MessageQueue.js:269:6
callFunctionReturnFlushedQueue
MessageQueue.js:107:17
How should I get the data?
I am index.ios.js inside οΌNext, how do I get the data?
import AppleHealthKit from 'rn-apple-healthkit';
let options = {
permissions: {
read: ["Height", "Weight", "StepCount", "DateOfBirth", "BodyMassIndex"],
write: ["Weight", "StepCount", "BodyMassIndex"]
}
};
When I tried to run the code, I am getting "_this2._handleHealthKitError is not a function" error. If I comment "this._handleHealthKitError () ", getting the result as { value: null, age: null }.
getSleepSamples() and getBloodPressureSamples() never return any data. I've triple checked that my app has permission to read data from HealthKit and that data is present however both functions never return any data. I think it's those functions particularly because calling getStepCount() with the same setup/options works fine
CODE:
//Pedometer permissions stuff
const HKPERMISSIONS = AppleHealthKit.Constants.Permissions;
//Options for all Apple Healthkit features
let OPTIONS = {
permissions: {
read: [HKPERMISSIONS.StepCount, HKPERMISSIONS.SleepAnalysis, HKPERMISSIONS.BloodPressureDiastolic, HKPERMISSIONS.BloodPressureSystolic],
write: [HKPERMISSIONS.StepCount]
}
};
let BLOODOPTIONS = {
unit: 'mmhg', // optional; default 'mmhg'
startDate: (new Date(2018,5,20)).toISOString(), // required
endDate: (new Date()).toISOString(), // optional; default now
ascending: false, // optional; default false
limit:10, // optional; default no limit
}
let SLEEPOPTIONS = {
startDate: (new Date(2018,5,20)).toISOString(), // required
endDate: (new Date()).toISOString(), // optional; default now
//limit:10, // optional; default no limit
};
...
AppleHealthKit.initHealthKit(OPTIONS, (err, res) => {
if(this._handleHealthKitError(err, 'initHealthKit')) {
return;
}
// healthkit initialized...
//Blood Pressure Example
AppleHealthKit.getBloodPressureSamples(BLOODOPTIONS, (err: Object, results: Array<Object>) => {
if (err) {
return;
}
console.warn("BLOOD: " + results);
});
//Sleep Analysis
AppleHealthKit.getSleepSamples(SLEEPOPTIONS, (err: Object, res:Array<Object>) => {
if (err) {
console.warn("ERROR: " + err)
return;
}
console.warn("SLEEP: " + res)
});
...
}
Why did I get this error?
In the documentation it states that you can write both systolic and diastolic blood pressure data. I read through the source code and can't find anything that seems to support this. Am I missing something?
11.3 (in beta as of this writing) adds many new healthkit constants because it uses FHIR to connect directly with electronic health systems, i.e. patient medical records. Is anyone working on adding these new data types to this library? For example LDL Cholesterol, or medications.
We are developing an App which give you "Coins" when you reached an achievement. You can manually enter step in Health Kit. Is it possible to filter out this manual entered data.
@terrillo I see that your last activity here was pretty long time ago. Do you have any plans for this library? I'd love to spend some effort to make this project live again
I'm using the code from the example from the original repo readme: https://www.npmjs.com/package/react-native-apple-healthkit#getdailystepcountsamples
const options = {
startDate: (new Date(2016,5,1)).toISOString(),
endDate: (new Date()).toISOString()
}
AppleHealthKit.getDailyStepCountSamples(options: Object, (err: Object, steps: Object) => {
if (err) {
console.log('error', err);
return;
}
console.log(steps)
});
This start date is obviously very long ago, but no matter what dates I set in the getDailyStepCountSamples I can only get the last 15 days of steps.
I am running on my device. Is this a bug or is it only possible to get the last 15 days? If I use other dates that start and end outside of the last 15 days I just get an empty array, no error.
Hi there,
iΒ΄m new with this topic..
is it possible to add a "saveDistaceCycling"-methods to the RCTAppleHealthKit+Methods_Fitness.m (*.h) script?
what do I have to consider?
thanks
Linus
It works well on iPhone 5 , iPhone 5s etc.
When I check this on iPhone X. The steps are in decimals. I receive the object in the format:
0: endDate:"2018-04-07T00:00:00.000+0530" startDate:"2018-04-06T00:00:00.000+0530" value:5213.434565464534535 __proto__:Object length:1 __proto__:Array(0)
I need to save distanceCycling, exerciseMinutes and heartRate
Thanks everyone
Is this library compatible with the latest versions of React Native? I can't get it to work, as there seems to be some issues with Header imports not being found. I've searched for hours with potential fixes such as changing the Header Search paths, but no luck.
'React/RCTBridgeModule.h' file not found
React Native Version
0.51.0
I've tried running Clean in Xcode after removing the rn-apple-healthkit and unlinking, then reinstalling again, still the issue persists.
Has anyone else been able to get it to build on newer versions of React Native?
This feature will add background observers for an arbitrary number of types of data. Below are my notes and ideas for how to implement this. Your comments and ideas are welcome.
I propose the following:
observe
let options = {
permissions: {
read: ["Height", "Weight", "StepCount", "DateOfBirth", "BodyMassIndex"],
write: ["Weight", "StepCount", "BodyMassIndex"],
},
observers: [
{ type: "StepCount" },
{ type: "Weight" }
]
};
AppleHealthKit.initHealthKit(options);
const healthKitData = await AsyncStorage.getItem('RNAppleHealthkit');
const steps = healthKitData.StepCount;
// `steps` might contains something like:
// [
// { date: '1 1 2019', value: 10000}
// ]
react-native-background-fetch
BackgroundFetch.configure({
minimumFetchInterval: 15, // <-- minutes (15 is minimum allowed)
}, () => {
// Retrieve data
const healthKitData = await AsyncStorage.getItem('RNAppleHealthkit');
// Stop if there isn't any
if (!healthKitData) {
BackgroundFetch.finish(BackgroundFetch.FETCH_RESULT_NO_DATA);
}
// Get steps
const steps = healthKitData.StepCount;
// Upload them
await fetch('http://placetouploadsteps.com/steps', { method: 'POST', body: JSON.stringify({ steps });
// No need to waste storage
AsyncStorage.removeItem('RNAppleHealthkit');
// Finish
BackgroundFetch.finish(BackgroundFetch.FETCH_RESULT_NEW_DATA);
}, (error) => {
console.log("[js] RNBackgroundFetch failed to start");
});
import { EventEmitter } from 'rn-apple-healthkit';
EventEmitter.addListener(
'change:StepCount',
(evt) => {
const steps = evt.data;
}
);
Perhaps I miss understand what is possible from the technology, but I want to get real-time step data for my users.
As an example, in part of the app, I want the user to go for a walk and get 500 steps. Can I not track these steps in realtime?
I tried getDailyStepCountSamples
and getStepCount
, but these are aggregations for a large time period. Is there any way to monitor a 5 to 10min interval and get the number of steps as they occur?
Update: Is this what I want? initStepCountObserver
Any way to get workout data?
Hey Everyone,
Looking to add collaborators. I'm going to start reviewing open pull requests and get the ball rolling again. π
Comment below if your interested in becoming a collaborator.
As mention above, how do i check permissions granted for certain action?
Please replace AppleHealthkit.initHealthKit
with AppleHealthKit.initHealthKit
(uppercase K in AppleHealthKit) in the last code snippet in the initHealthKit() wiki.
EDIT: This typo is repeated in many other Wiki pages as well.
Hey,
I'm calling the "getStepCount()" method without any option, its getting the current date (default value), but if I set in the options(dictionary) a date key and a value its returning an error 'could not fetch step count for day' . anyone having the same issue?
following this link: https://github.com/terrillo/rn-apple-healthkit/wiki/getStepCount()
Hello,
Is it possible to add the following functions? I would like to insert as well as read out blood clucose values. Additionally, I would like to save as well as read out carbohydrate values (https://developer.apple.com/documentation/healthkit/hkquantitytypeidentifier/1615699-dietarycarbohydrates). Would it be possible for you to provide this?
I have a few questions about 'save food' feature:
Why it is not presented in read me while it is available in the source code?
I found that saveFood is not very stable. Sometimes it saves food, but most of the time it doesn't. Also, the callback function is not getting called when it doesn't save, which makes it is very hard to suggest what is going wrong. Any thoughts about it?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. πππ
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google β€οΈ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.