Coder Social home page Coder Social logo

ovalmoney / react-native-fitness Goto Github PK

View Code? Open in Web Editor NEW
341.0 12.0 68.0 252 KB

A React Native module to interact with Apple Healthkit and Google Fit.

License: MIT License

Java 52.09% JavaScript 3.63% Ruby 1.02% Objective-C 43.26%
react-native android ios apple-health google-fit fitness

react-native-fitness's Introduction

react-native-fitness

react-native-fitness is a library that works on both iOS and Android with it you can interact with Apple Healthkit and Google Fit. Currently the lib provides a set of API that you can use to read steps count or distance count for a given period of time.

Note: We're open to receive PRs that contains new features or improvements, so feel free to contribute to this repo.

Getting started

npm install @ovalmoney/react-native-fitness --save

or

yarn add @ovalmoney/react-native-fitness

Mostly automatic installation

react-native link @ovalmoney/react-native-fitness

Manual installation

iOS

Pods

  1. Add the line below to your Podfile.
    pod 'react-native-fitness', :path => '../node_modules/@ovalmoney/react-native-fitness'`
    
  2. Run pod install in your iOS project directory.
  3. In XCode, select your project, go to Build PhasesLink Binary With Libraries and add libreact-native-fitness.a.
  4. Add following to your Info.plist in order to ask permissions.
    <key>NSHealthShareUsageDescription</key>
    <string>Read and understand health data.</string>

Manually

  1. In XCode's project navigator, right click LibrariesAdd Files to [your project's name]
  2. Go to node_modules@ovalmoneyreact-native-fitness and select RNFitness.xcodeproj
  3. In XCode select your project, go to Build PhasesLink Binary With Libraries and add libRNFitness.a.
  4. Run your project (Cmd+R)

In order to make it run, it is necessary to turn on Health Kit in the Capabilities.

Android

  1. Get an OAuth 2.0 Client ID as explained at https://developers.google.com/fit/android/get-api-key
  2. Open up MainApplication.java
    • Add import com.ovalmoney.fitness.RNFitnessPackage; to the imports at the top of the file
    • Add new RNFitnessPackage() to the list returned by the getPackages() method
  3. Append the following lines to android/settings.gradle:
    include ':@ovalmoney_react-native-fitness'
    project(':@ovalmoney_react-native-fitness').projectDir = new File(rootProject.projectDir, 	'../node_modules/@ovalmoney/react-native-fitness/android')
  4. Insert the following lines inside the dependencies block in android/app/build.gradle:
    compile project(':@ovalmoney_react-native-fitness')
  5. (Optional) In order to better handle the right versions, add in your android/build.gradle:
      // Other build versions
      fitnessPlayServices: "<Your version>" // default: 17.0.0
      authPlayServices: "<Your version>" // default: 17.0.0
    }
    

Usage

import Fitness from '@ovalmoney/react-native-fitness';

const permissions = [
  { kind: Fitness.PermissionKinds.Steps, access: Fitness.PermissionAccesses.Write },
];

Fitness.isAuthorized(permissions)
  .then((authorized) => {
    // Do something
  })
  .catch((error) => {
    // Do something
  });

API

  • Fitness.isAuthorized([{ kind: int, access: int }]) Check if permissions are granted or not. It works on Android and iOS >= 12.0, while it returns an error when iOS < 12. It requires an Array of Object with a mandatory key kind and an optional key access. Possible values for the keys can be found in PermissionKinds and PermissionAccesses under Attributes section. On iOS at least one permissions with Read access must be provided, otherwise an errorEmptyPermissions will be thrown.

  • Fitness.requestPermissions([{ kind: int, access: int }]) Ask permission and return if user granted or not(Android), while, due to Apple's privacy model, always true is returned in iOS. It requires an Array of Object with a mandatory key kind and an optional key access. Possible values for the keys can be found in PermissionKinds and PermissionAccesses under Attributes section. On iOS at least one permissions with Read access must be provided, otherwise an errorEmptyPermissions will be thrown.

  • Fitness.logout() Available only on android. It performs a logout from google account. It returns true for a successful logout, false if user cancel action.

  • Fitness.disconnect() Available only on android. It performs a disconnect action from Google Fit. It returns true for a successful logout, false if user cancel action.

  • Fitness.getSteps({ startDate: string, endDate: string, interval: string }) Fetch steps on a given period of time. It requires an Object with startDate and endDate attributes as string. If startDate is not provided an error will be thrown. Set interval to decide how detailed the returned data is, set it to hour or minute otherwise it defaults to days.

  • Fitness.getDistances({ startDate: string, endDate: string, interval: string }) Fetch distance in meters on a given period of time. It requires an Object with startDate and endDate attributes as string. If startDate is not provided an error will be thrown. Set interval to decide how detailed the returned data is, set it to hour or minute otherwise it defaults to days.

  • Fitness.getCalories({ startDate: string, endDate: string, interval: string }) Fetch calories burnt in kilocalories on a given period of time. It requires an Object with startDate and endDate attributes as string. If startDate is not provided an error will be thrown. Set interval to decide how detailed the returned data is, set it to hour or minute otherwise it defaults to days.

  • Fitness.getHeartRate({ startDate: string, endDate: string, interval: string }) Fetch heart rate bpm on a given period of time. It requires an Object with startDate and endDate attributes as string. If startDate is not provided an error will be thrown. Set interval to decide how detailed the returned data is, set it to hour or minute otherwise it defaults to days.

  • Fitness.getSleepAnalysis({ startDate: string, endDate: string }) Fetch sleep analysis data on a given period of time. It requires an Object with startDate and endDate attributes as string. If startDate is not provided an error will be thrown.

  • Fitness.subscribeToSteps() Available only on android. Subscribe only to steps from the Google Fit store. It returns a promise with true for a successful subscription and false otherwise. Call this function to get steps and eliminate the need to have Google Fit installed on the device.

Attributes

Platform

Return the used provider.

PermissionKinds

Return the information of what kind of Permission can be asked. At the moment the list of possible kinds is:

  • Steps: to required the access for Steps
  • Distances: to required the access for Distances
  • Calories: to required the access for Calories
  • HeartRate: to required the access for Heart rate
  • Activity: to required the access for Activity (only Android)
  • SleepAnalysis: to required the access for Sleep Analysis

PermissionAccesses

Return the information of what kind of Access can be asked. The list of possible kinds is:

  • Read: to required the access to Read
  • Write: to required the access to Write

Errors

Return the list of meaningful errors that can be possible thrown.

iOS

Possible values are:

  • hkNotAvailable: thrown if HealthKit is not available
  • methodNotAvailable: thrown if isAuthorized is called on iOS < 12.0
  • dateNotCorrect: thrown if received date is not correct
  • errorEmptyPermissions: thrown if no read permissions are provided
  • errorNoEvents: thrown if an error occurs while try to retrieve data
Android

Possible values are:

  • methodNotAvailable: thrown if getSleepAnalysis is called on Android less than N

react-native-fitness's People

Contributors

cruelmoney avatar dmitov avatar francesco-voto avatar gudninathan avatar ibraude avatar lasalefamine avatar orenzak avatar renelems avatar rlems avatar scerelli avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-fitness's Issues

google pixel 3a get empty array

I am using a pixel 3a mobile phone, Android 10, google fit authorization is successful, but I get the empty array of steps, please help

Update documentation

Please update your documentation for iOS and Android and include code snippets for running your code.

Failed to Compile on Android

My App cannot be compiled to Android due to usage of deprecated API

macOS Version
Catalina 10.15.5

Java Environment
java version "1.8.0_161"
Java(TM) SE Runtime Environment (build 1.8.0_161-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.161-b12, mixed mode)

React Native Version
v0.62.2

react-native-fitness
v0.4.0

Step to reproduce
run yarn run android

Screen Shot 2020-09-03 at 21 49 10

hour interval not working on Android

I'm trying to get the steps in hours. It works for iOS, but not for Android devices. On Android it still returns the steps per day for me.
If I manually alter the node_modules/@ovalmoney/react-native-fitness/android/src/main/java/com/ovalmoney/fitness/manager/Manager.java and set

interval = TimeUnit.HOURS;

it does work.

This is my code:

function getSteps(startDate, endDate, interval = 'hour') {
  return Fitness.getSteps({ startDate, endDate, interval })
    .catch(e => {
      console.error('getSteps error', e);
    });
}

And I call this function like this:

const res = await getSteps(startDate, endDate);

The resulting value of res is

[
  { quantity: 815, endDate: "2020-05-27T23:16:07.643+0200", startDate: "2020-05-27T07:17:11.227+0200" },
  { quantity: 8808, endDate: "2020-05-29T00:00:00.000+0200", startDate: "2020-05-28T07:34:28.192+0200" },
  { quantity: 1802, endDate: "2020-05-29T23:31:36.275+0200", startDate: "2020-05-29T00:00:00.000+0200" },
  { quantity: 1128, endDate: "2020-05-30T23:47:59.406+0200", startDate: "2020-05-30T00:28:58.019+0200" },
  { quantity: 1109, endDate: "2020-05-31T21:26:37.564+0200", startDate: "2020-05-31T00:40:05.296+0200" },
  { quantity: 393, endDate: "2020-06-01T23:00:21.904+0200", startDate: "2020-06-01T01:41:36.727+0200" },
  { quantity: 333, endDate: "2020-06-02T10:52:22.654+0200", startDate: "2020-06-02T07:12:06.461+0200" }
]

Any idea why this is happening?

error: cannot find symbol: variable TYPE_ACTIVITY_SAMPLES

Screenshot 2020-08-11 at 10 20 51 PM

node_modules/@ovalmoney/react-native-fitness/android/src/main/java/com/ovalmoney/fitness/manager/Manager.java:145: error: cannot find symbol
.subscribe(DataType.TYPE_ACTIVITY_SAMPLES)
^
symbol: variable TYPE_ACTIVITY_SAMPLES
location: class DataType

It was working fine, suddenly stopped working today after npm install for other library

react-native 0.62.0
@ovalmoney/react-native-fitness: 0.4.0

Unable to Authorize with Google Fit

@scerelli I am trying to authorise the app to connect to google fit, but the Fitness.requestPermissions method always returns false. Is there some specific requirements for android? I saw a merge request #6 which was intended to allow connection even without Google Fit installed.

I am using react-native 0.60.6, lib version 0.2.4 and Android Q (API level 29) emulator. Any idea what could be wrong?

Not getting Steps data of present day (today) correctly.

I am trying to get steps data in android. In google fit I have the following steps data:
May 3, 2020 : 124 Steps
May 4, 2020: 3958 Steps
May 5, 2020: 61 Steps
When I am trying to get the data of May 3 to May 5 with startDate 2020-05-03 and endDate 2020-05-05 I am getting following data
[ { quantity: 123,
│ endDate: '2020-05-04T04:11:07.402+0600',
│ startDate: '2020-05-03T09:10:01.770+0600' },
│ { quantity: 4012,
│ endDate: '2020-05-05T02:27:37.798+0600',
└ startDate: '2020-05-04T11:59:28.624+0600' } ]

Is there anything regarding timezone?

java.lang.NullPointerException: null reference

java.lang.NullPointerException: null reference
at com.google.android.gms.common.internal.Preconditions.checkNotNull(Unknown Source)
at com.google.android.gms.fitness.Fitness.getHistoryClient(Unknown Source)
at com.ovalmoney.fitness.manager.Manager.getCalories(Manager.java:353)
at com.ovalmoney.fitness.RNFitnessModule.getCalories(RNFitnessModule.java:167)
at java.lang.reflect.Method.invoke(Native Method)
at com.facebook.react.bridge.JavaMethodWrapper.invoke(JavaMethodWrapper.java:372)
at com.facebook.react.bridge.JavaModuleWrapper.invoke(JavaModuleWrapper.java:151)
at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:27)
at android.os.Looper.loop(Looper.java:165)
at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(MessageQueueThreadImpl.java:226)
at java.lang.Thread.run(Thread.java:760)

Can't get any results...

Hello,

I cant seem to get any results returned from either Fitness.getSteps or Fitness.getDistance.
I have tested this on a simulator with manually entered data in the HealthKit as well as on a device that has walking distance and steps data for each day... (iOS)

The code that I am using is the following:

let theDates = { startDate: "2019-12-02", endDate: "2019-12-03" };

let steps = Fitness.getSteps(theDates);

console.log("Steps...");
console.log(steps);

All it returns for any date or combination of dates is :

Steps...
{"_40": 0, "_55": null, "_65": 0, "_72": null}

I have double checked and the application does have access to the HealthKit data.
Any help will be greatly appreciated!!

Have an awesome day!

Query for Immediate Values

Hey!

I've been testing out this lib to query step count and heart rate on an interval (like every 5 seconds). I noticed that the data that is returned takes about 5 minutes to update. I was wondering if there is a way to get immediate values? I did some research on different querying mechanisms in HK but, I'm still a little unsure of if this is possible on such a short frequency.

Thanks!

getCalories error

catch error TypeError: _reactNativeFitness.default.getCalories is not a function

const dates = { startDate: withinDay(7), endDate: new Date().toISOString() }
Fitness.getCalories(dates).then(result => {
console.log('getCalories Result ' + JSON.stringify(result))
});

Bug: getDistance

Hello,

in the Readme and index.d.ts the method is defined as getDistances()
But the actual implementation is getDistance()

Feature request - weight, height, bmi, dob, sex

Hi, this looks like a really nice package with a clean api.

Any plans of adding support for reading/writing these additional data types? I know they are available on iOS, but I don't know about Android.

How to use google fit without download the google fit app in android device?

I am using the react-native-fitness version 0.4.0 and react-native version 0.63.2.
I am getting an empty array in return of calling getCalories function until i install Google Fit app on my android phone. I don't want to install google fit app, but without it function returns me empty array.
There must be a way around, Please suggest.

Feature request - add minute interval

Thanks for the library, seems to work great! But for a use case of mine I need to be able to retrieve the steps per minute. I see that the interval on iOS and Android can be any kind of time value, including minute. Could that be supported?

I'll try to create a PR myself for this.

Usage example

Hey,

First of all, thank you very much for the module.
I was wondering if you could post a usage example using the getSteps method.

I have set up the module, including the Google Client ID.
the requestPermission method works, and I get true from isAuthorized, but for the getSteps method, I just get an empty array as the response and can't seem to get a step count.
Fitness.getSteps({startDate: start, endDate:end}) .then((response) => {console.log(response)}) //logs []

How would you go about using the module to get an ongoing step count?

Any insight would be greatly appreciated.

Thanks,

getDistance not working

Hi all,

I was trying to using the permission and the method getDistance unfortunately the permission is not asked, just the permission for the steps, so neither the value is visible and usable

Feature request - Option to filter manually entered data

Hi and thanks for this neat package!

I'm submitting a feature request for the possibility to left out user entered data when querying for distance/steps. This would enable to use only "real" data.

As a test, I managed to implement it in the iOs version of GetSteps by doing the following:

  • Declare a predicate that leaves out User Entered data

NSPredicate *sourcePredicate = [NSPredicate predicateWithFormat:@"metadata.%K != YES", HKMetadataKeyWasUserEntered];

  • Use this predicate when querying:

HKStatisticsCollectionQuery *query = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:type quantitySamplePredicate:nil options:HKStatisticsOptionCumulativeSum anchorDate:anchorDate intervalComponents:interval];

I'd like to work on that feature request, but I do not master Swift nor Java and haven't experienced working on a bridge between RN and Native. I'm more than happy to help you, let me know how I could proceed!

Cheers

Fitness.getSleepAnalysis(dateSleep) returns empty array

I don't know what can be a reason here but getSteps is working fine and I'm getting steps from start to end date but not in case I try to get sleep analysis , any idea what can be a reason ?

 let dateSleep = 
      {startDate: '2020-04-01', endDate:'2021-04-19' };
 Fitness.getSleepAnalysis(dateSleep)
        .then((records) => {
          console.log("here came",records)
          //console.log("here",Fitness.SleepAnalysis.records)
          // Do something
        })
        .catch((error) => {
          console.log("here",error)
          // Do something
        });
      }

error: null reference. when I do console.log, isAuthorized always return false, PermissionAccess.write always return undefined

Hello,

First of all, great work! Im so excited to try this plugin.
I tried using this with RN 0.62, (using autolinking).
if I run without checking isAuthorized, it always gives null reference error. So, I put some console.log(s) and found out isAuthorized always return false, PermissionAccess.write always return undefined.
Did I miss a step in setting up this plugin, or maybe there's missing step in the usage?

Thanks in advance, pardon if the snippet is a bit messy

const permissions = [ { kind: Fitness.PermissionKind.Step, access: Fitness.PermissionAccess.Write } ];

`const logSteps = async () => {

console.log("permission:", permissions); // the result is {access: undefined, kind: 0}
Fitness.isAuthorized(permissions)
  .then(async (authorized) => {
    let initialDate = new Date();
    let startDate = new Date(initialDate.getFullYear(), initialDate.getMonth(), initialDate.getDate(), 0, 0, 0);
    let endDate = new Date(initialDate.getFullYear(), initialDate.getMonth(), initialDate.getDate(), 23, 59, 59);
    let formattedStart = startDate.toISOString();
    let formattedEnd = endDate.toISOString();
    console.log('start:', formattedStart);
    console.log('end:', formattedEnd);
    // Do something
    console.log('auth result:', authorized); // always return false
    if(authorized){
      let result = await Fitness.getSteps({
        startDate: formattedStart,
        endDate: formattedEnd,
        interval: 'days'
      });
    }
  })
  .catch((error) => {
    // Do something
    console.log('Failed auth', error);
  });

}
`

Fitness.requestPermissions(permissions) does not show permission allow modal

Fitness.requestPermissions(permissions) .then((authorized) => { console.log({authorized}); }) .catch((error) => { console.log({error}); });

When i login into permission with my google account it keeps loading. I followed all steps and double checked all of them but does not stop loading keeps loading and does not ask me permission help 😃

Android getSteps error

First, thanks for writing this module. works great on iOS.

my code
.
.
.
const dates = { startDate: new Date(before).toISOString(), endDate: new Date().toISOString(),interval:"days"}
await Fitness.getSteps(dates).then(result => {
healthIsAvailable = true;
stepsWeek = result;
stepsToday = result[result.length-1].quantity;
return
})
.catch((error) => {
console.log("getStepserror",error);
});
.
.
.

I get an error on Android "Fitness.getSteps got 4 arguments, expected 5"

Anya ideas why? there are no more arguments to send is there?

Log from Android Studio:

01-14 11:38:31.835 14328-14390/se.act4yourheart E/unknown:ReactNative: Exception in native call
com.facebook.react.bridge.NativeArgumentsParseException: Fitness.getSteps got 4 arguments, expected 5
at com.facebook.react.bridge.JavaMethodWrapper.invoke(JavaMethodWrapper.java:348)
at com.facebook.react.bridge.JavaModuleWrapper.invoke(JavaModuleWrapper.java:150)
at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:26)
at android.os.Looper.loop(Looper.java:148)
at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(MessageQueueThreadImpl.java:225)
at java.lang.Thread.run(Thread.java:818)

App crash on bundleRelease version

The app crashed on Android when a users wants to choose a google account (on the oAuth screen). This only happens on the bundleRelease version and not on debug or the apk production version (so really only on the bundle release version that you'd upload to play console).
The app also already has a OAuth 2.0 Client ID with the scopes activity.read and location.read.

The weird thing is that I can't really debug it that well because the release version works, just not when I upload and install it via play console.
./gradlew installRelease works fine
./gradlew bundleRelease and uploading to play console and installing it makes the app crash when clicking the on an account in the oAuth screen.

02-22 10:51:41.211  6670  6724 E AndroidRuntime: FATAL EXCEPTION: mqt_native_modules
02-22 10:51:41.211  6670  6724 E AndroidRuntime: Process: com.example.app, PID: 6670
02-22 10:51:41.211  6670  6724 E AndroidRuntime: java.lang.NullPointerException: null reference
02-22 10:51:41.211  6670  6724 E AndroidRuntime: 	at com.google.android.gms.common.internal.p.i(Unknown Source:7)
02-22 10:51:41.211  6670  6724 E AndroidRuntime: 	at e.d.a.b.e.c.b(Unknown Source:0)
02-22 10:51:41.211  6670  6724 E AndroidRuntime: 	at com.ovalmoney.fitness.b.a.l(Unknown Source:68)
02-22 10:51:41.211  6670  6724 E AndroidRuntime: 	at com.ovalmoney.fitness.RNFitnessModule.getSteps(Unknown Source:10)
02-22 10:51:41.211  6670  6724 E AndroidRuntime: 	at java.lang.reflect.Method.invoke(Native Method)
02-22 10:51:41.211  6670  6724 E AndroidRuntime: 	at com.facebook.react.bridge.JavaMethodWrapper.invoke(Unknown Source:147)
02-22 10:51:41.211  6670  6724 E AndroidRuntime: 	at com.facebook.react.bridge.JavaModuleWrapper.invoke(Unknown Source:21)
02-22 10:51:41.211  6670  6724 E AndroidRuntime: 	at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)
02-22 10:51:41.211  6670  6724 E AndroidRuntime: 	at android.os.Handler.handleCallback(Handler.java:883)
02-22 10:51:41.211  6670  6724 E AndroidRuntime: 	at android.os.Handler.dispatchMessage(Handler.java:100)
02-22 10:51:41.211  6670  6724 E AndroidRuntime: 	at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(Unknown Source:0)
02-22 10:51:41.211  6670  6724 E AndroidRuntime: 	at android.os.Looper.loop(Looper.java:214)
02-22 10:51:41.211  6670  6724 E AndroidRuntime: 	at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(Unknown Source:37)
02-22 10:51:41.211  6670  6724 E AndroidRuntime: 	at java.lang.Thread.run(Thread.java:919)

requestPermissions always return true [iOS]

When I'm tried using requestPermissions on iOS I'm getting issue it's always return true. When the user click Don't Allow it shows up an alert like this and then return true. After that, I tried using function isAuthorized and it always returns true.
Screen Shot 2020-04-12 at 4 20 06 PM

Anyone can help me resolve this issue?

Feature request - Get flights/floor data

Hi guys!

Thanks a lot for this library! I would like to integrate the amount of floors/flights climbed in my app. Could you point me in the right direction or is this something you are willing to implement? For now iOS HealthKit data is enough for my use case.

_reactNativeFitness.default.PermissionKind.Step is undefined

Copying straight out of the example, I have this code here:

import Fitness from '@ovalmoney/react-native-fitness';

getHealthData = () => {
    const permissions = [
      { kind: Fitness.PermissionKind.Step, access: Fitness.PermissionAccess.Write },
    ];

    Fitness.isAuthorized(permissions)
      .then((authorized) => {
        console.warn(Fitness.getSteps({ startDate: new Date(2020, 4, 12) }))
      })
      .catch((error) => {
        // Do something
      });
  };

However, it's throwing me an error saying that PermissionKind.Step is undefined. Any idea to why this might be?

How to uninstall on iOS ?

Hi, how to uninstall package, and exclude it from iOS Project. We have some problem when publishin to App Store, thanks 😊

Android promises not resolving

Hi,
Thanks you for the library which works flawlessly on iOS. I am encountering an issue with the android part : whenever I try to call Fitness.getSteps(opt) or Fitness.getDistance(opt), the promises created won't resolve nor reject.

I made sure that my SHA1 is properly authorized through the Google Fitness API & co (as other functions such as Fitness.isAuthorized() properly works).

I'm on RN 0.59.10 with the library at 0.2.4

0.60 support?

Hi guys, good stuff!

I'm interested what's the support for RN 0.60 and automatic linking?

Also, is there a roadmap or a feature list so I can help with the development?

requestPermissions does not ask user for permissions

Below is the code that I am using. When I call requestPermissions it does not ask the user for permissions. Please assist

export function useRequestPermissions() {
  const [loading, setLoading] = useState(false);
  const [granted, setGranted] = useState(false);

  useEffect(() => {
    setLoading(true);
    Fitness.requestPermissions(permissions)
      .then(authorized => {
        console.log({ authorized });
        setGranted(authorized);
        setLoading(false);
      })
      .catch(error => {
        console.log({ error });
        setGranted(false);
      });
  }, []);

  return {
    loading,
    granted,
  };
}```

[Android] Application needs OAuth consent from the user

This Error happen with getHeartRate method
while the othes methods are working fine after sign in and allow permissions (permission HeartRate included).


const permissions = [
{
kind: Fitness.PermissionKinds.Steps,
access: Fitness.PermissionAccesses.Read,
},
{
kind: Fitness.PermissionKinds.Calories,
access: Fitness.PermissionAccesses.Read,
},
{
kind: Fitness.PermissionKinds.Distances,
access: Fitness.PermissionAccesses.Read,
},
{
kind: Fitness.PermissionKinds.HeartRate,
access: Fitness.PermissionAccesses.Read,
},
];


let currentDate = new Date();
let start = new Date(2021, 1, 1, 0, 0, 0);
let end = new Date( currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), 23, 59, 59,);

const getHeartRate = () => {
Fitness.getHeartRate({ startDate: start, endDate: end, interval: 'days' })
.then((res) => {
console.log('getHeartRate', res);
})
.catch((e) => {
console.log('error', e);
});
};


Screen Shot 2021-02-26 at 16 09 13
Screen Shot 2021-02-26 at 16 48 51
Screen Shot 2021-02-26 at 16 59 23

on IOS , getCalories return []

Hello everyone, my authorization is successful on ios, and both step and distance can get data, but on the debug and release packages, getCalories method return [], has anyone encountered this problem ?
image

How to get the real data of google fit?

because you can add the number of fake steps in Google fit, so how do you make sure you use it Fitness.getSteps () the number of steps obtained is the actual sensor step number, not the number of steps added by the user?

Getting error "No events found"

I had tried using Fitness.isAuthorized(permissions) it returns false and then I'm trying to get request permission, I'm getting error No events found.

Here is my code:
const permissions = [ { kind: Fitness.PermissionKind.Step, access: Fitness.PermissionAccess.Read }, ]; Fitness.requestPermissions(permissions).then(res => { console.log('res', res); }).catch(err => { console.log('err', err); // No events found })

Anyone can help me fix this issues?

RESULTS.UNAVAILABLE on android 9

Authorization is successful on Android 10, but on Android 9, the result returned by check(PERMISSIONS.ANDROID.ACTIVITY_RECOGNITION) is RESULTS.UNAVAILABLE,

I have added these 2 permissions ,Does anyone know the reason ?

iOS: isAuthorized does not work

Hello,

I was trying to see if the user, has given the app the permissions..

I think the wrong method is used:

[self.healthStore getRequestStatusForAuthorizationToShareTypes: sharePerms readTypes: readPerms completion:^(HKAuthorizationRequestStatus status, NSError *error) {

Because HKAuthorizationRequestStatus is compared against HKAuthorizationStatus
https://developer.apple.com/documentation/healthkit/hkauthorizationrequeststatus?language=objc

This method to my understanding only returns, if a popup will appear on requesting the permission, but won't tell if the app is authorised or not.

I think this method, is the right one https://developer.apple.com/documentation/healthkit/hkhealthstore/1614154-authorizationstatus
But as the documentation states.. it will only work on write not for read

Greets
Michael

Can't get the latest release of this library

Hi there!

When I try to install the latest release of this library (v0.2.5) using

npm install @ovalmoney/react-native-fitness --save

npm installs me the v0.2.4 instead of v0.2.5. If I enforce to install the v0.2.5 it tells me

Couldn't find any versions for "@ovalmoney/react-native-fitness" that matches "^0.2.5"

How do I proceed?

Regards,

getSteps return empty array

As @ibraude mentioned before I still get the empty array. It works on both android & IOS like authorizaiton etc. but when I get results of steps its just empty array. I thought it could be cuz of simulator but I test it in real device now, looks same..

Permissions:

const permissions = [
          {
              kind: Fitness.PermissionKind.Step,
              access: Fitness.PermissionAccess.Read
          },
];

Can anyone help about it?

Nutrients access?

I can see both Google Fit and Apple Healthkit provide information on nutrients. Is it possible to access this through this tool? Or if not, how hard would it be to add this as a feature?

Get Access Token from Fitness.requestPermissions()

Hi,

I am trying to fetch the access token on the android device after the user authorize by Fitness requestPermissions() and then send access token to my backend server so that we can fetch steps data using Google Fit Rest API.

How To Logout

I was able to connect to Google Fitness, and Apple Healthkit,

Now how to disconnect or log out user from their account, in case they want to use different account, or they log out for my application

thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.