Commit b0d36545 authored by 冷佳娟's avatar 冷佳娟 💪

Merge branch 'terrillo' into develop

# Conflicts:
#	RCTAppleHealthKit/RCTAppleHealthKit+Methods_Fitness.h
#	RCTAppleHealthKit/RCTAppleHealthKit+Methods_Fitness.m
#	RCTAppleHealthKit/RCTAppleHealthKit+Queries.m
#	RCTAppleHealthKit/RCTAppleHealthKit+Utils.m
#	RCTAppleHealthKit/RCTAppleHealthKit.m
parents fbeb3980 5395cd79
...@@ -16,8 +16,46 @@ export const Permissions = { ...@@ -16,8 +16,46 @@ export const Permissions = {
BodyMassIndex: "BodyMassIndex", BodyMassIndex: "BodyMassIndex",
BodyTemperature: "BodyTemperature", BodyTemperature: "BodyTemperature",
DateOfBirth: "DateOfBirth", DateOfBirth: "DateOfBirth",
DietaryEnergy: "DietaryEnergy", Biotin: "Biotin",
Caffeine: "Caffeine",
Calcium: "Calcium",
Carbohydrates: "Carbohydrates",
Chloride: "Chloride",
Cholesterol: "Cholesterol",
Copper: "Copper",
EnergyConsumed: "EnergyConsumed",
FatMonounsaturated: "FatMonounsaturated",
FatPolyunsaturated: "FatPolyunsaturated",
FatSaturated: "FatSaturated",
FatTotal: "FatTotal",
Fiber: "Fiber",
Folate: "Folate",
Iodine: "Iodine",
Iron: "Iron",
Magnesium: "Magnesium",
Manganese: "Manganese",
Molybdenum: "Molybdenum",
Niacin: "Niacin",
PantothenicAcid: "PantothenicAcid",
Phosphorus: "Phosphorus",
Potassium: "Potassium",
Protein: "Protein",
Riboflavin: "Riboflavin",
Selenium: "Selenium",
Sodium: "Sodium",
Sugar: "Sugar",
Thiamin: "Thiamin",
VitaminA: "VitaminA",
VitaminB12: "VitaminB12",
VitaminB6: "VitaminB6",
VitaminC: "VitaminC",
VitaminD: "VitaminD",
VitaminE: "VitaminE",
VitaminK: "VitaminK",
Zinc: "Zinc",
Water: "Water",
DistanceCycling: "DistanceCycling", DistanceCycling: "DistanceCycling",
DistanceSwimming: "DistanceSwimming",
DistanceWalkingRunning: "DistanceWalkingRunning", DistanceWalkingRunning: "DistanceWalkingRunning",
FlightsClimbed: "FlightsClimbed", FlightsClimbed: "FlightsClimbed",
HeartRate: "HeartRate", HeartRate: "HeartRate",
...@@ -29,5 +67,6 @@ export const Permissions = { ...@@ -29,5 +67,6 @@ export const Permissions = {
SleepAnalysis: "SleepAnalysis", SleepAnalysis: "SleepAnalysis",
StepCount: "StepCount", StepCount: "StepCount",
Steps: "Steps", Steps: "Steps",
Weight: "Weight" Weight: "Weight",
Workout: "Workout"
} }
Pod::Spec.new do |s|
s.name = "RCTAppleHealthKit"
s.summary = "A React Native bridge module for interacting with Apple Healthkit data"
s.version = "0.6.5"
s.homepage = "https://github.com/terrillo/rn-apple-healthkit"
s.license = "MIT"
s.author = { "Terrillo Walls" => "terrillo@terrillo.com" }
s.platform = :ios, "9.0"
s.source = { :git => "https://github.com/terrillo/rn-apple-healthkit", :tag => "master" }
s.source_files = "RCTAppleHealthKit/*.{h,m}"
s.requires_arc = true
s.dependency "React"
end
\ No newline at end of file
...@@ -16,6 +16,7 @@ ...@@ -16,6 +16,7 @@
3774C8D71D20C65F0000B3F3 /* RCTAppleHealthKit+Methods_Fitness.m in Sources */ = {isa = PBXBuildFile; fileRef = 3774C8D61D20C65F0000B3F3 /* RCTAppleHealthKit+Methods_Fitness.m */; }; 3774C8D71D20C65F0000B3F3 /* RCTAppleHealthKit+Methods_Fitness.m in Sources */ = {isa = PBXBuildFile; fileRef = 3774C8D61D20C65F0000B3F3 /* RCTAppleHealthKit+Methods_Fitness.m */; };
377D44F31D247D0A004E35CB /* RCTAppleHealthKit+Methods_Characteristic.m in Sources */ = {isa = PBXBuildFile; fileRef = 377D44F21D247D0A004E35CB /* RCTAppleHealthKit+Methods_Characteristic.m */; }; 377D44F31D247D0A004E35CB /* RCTAppleHealthKit+Methods_Characteristic.m in Sources */ = {isa = PBXBuildFile; fileRef = 377D44F21D247D0A004E35CB /* RCTAppleHealthKit+Methods_Characteristic.m */; };
37837E7D1DCFE270000201A0 /* RCTAppleHealthKit+Methods_Sleep.m in Sources */ = {isa = PBXBuildFile; fileRef = 37837E7C1DCFE270000201A0 /* RCTAppleHealthKit+Methods_Sleep.m */; }; 37837E7D1DCFE270000201A0 /* RCTAppleHealthKit+Methods_Sleep.m in Sources */ = {isa = PBXBuildFile; fileRef = 37837E7C1DCFE270000201A0 /* RCTAppleHealthKit+Methods_Sleep.m */; };
58C81E6F1F84F6970005DD48 /* RCTAppleHealthKit+Methods_Activity.m in Sources */ = {isa = PBXBuildFile; fileRef = 58C81E6D1F84F6970005DD48 /* RCTAppleHealthKit+Methods_Activity.m */; };
61232F931E303758000A5026 /* RCTAppleHealthKit+Methods_Mindfulness.m in Sources */ = {isa = PBXBuildFile; fileRef = 61232F921E303758000A5026 /* RCTAppleHealthKit+Methods_Mindfulness.m */; }; 61232F931E303758000A5026 /* RCTAppleHealthKit+Methods_Mindfulness.m in Sources */ = {isa = PBXBuildFile; fileRef = 61232F921E303758000A5026 /* RCTAppleHealthKit+Methods_Mindfulness.m */; };
64C42D4A1D351A8800A0A8F7 /* RCTAppleHealthKit+Methods_Vitals.m in Sources */ = {isa = PBXBuildFile; fileRef = 64C42D491D351A8800A0A8F7 /* RCTAppleHealthKit+Methods_Vitals.m */; }; 64C42D4A1D351A8800A0A8F7 /* RCTAppleHealthKit+Methods_Vitals.m in Sources */ = {isa = PBXBuildFile; fileRef = 64C42D491D351A8800A0A8F7 /* RCTAppleHealthKit+Methods_Vitals.m */; };
64E0E73F1D37947B00EAB905 /* RCTAppleHealthKit+Methods_Results.m in Sources */ = {isa = PBXBuildFile; fileRef = 64E0E73E1D37947B00EAB905 /* RCTAppleHealthKit+Methods_Results.m */; }; 64E0E73F1D37947B00EAB905 /* RCTAppleHealthKit+Methods_Results.m in Sources */ = {isa = PBXBuildFile; fileRef = 64E0E73E1D37947B00EAB905 /* RCTAppleHealthKit+Methods_Results.m */; };
...@@ -53,6 +54,8 @@ ...@@ -53,6 +54,8 @@
377D44F21D247D0A004E35CB /* RCTAppleHealthKit+Methods_Characteristic.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "RCTAppleHealthKit+Methods_Characteristic.m"; sourceTree = "<group>"; }; 377D44F21D247D0A004E35CB /* RCTAppleHealthKit+Methods_Characteristic.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "RCTAppleHealthKit+Methods_Characteristic.m"; sourceTree = "<group>"; };
37837E7B1DCFE270000201A0 /* RCTAppleHealthKit+Methods_Sleep.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "RCTAppleHealthKit+Methods_Sleep.h"; sourceTree = "<group>"; }; 37837E7B1DCFE270000201A0 /* RCTAppleHealthKit+Methods_Sleep.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "RCTAppleHealthKit+Methods_Sleep.h"; sourceTree = "<group>"; };
37837E7C1DCFE270000201A0 /* RCTAppleHealthKit+Methods_Sleep.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "RCTAppleHealthKit+Methods_Sleep.m"; sourceTree = "<group>"; }; 37837E7C1DCFE270000201A0 /* RCTAppleHealthKit+Methods_Sleep.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "RCTAppleHealthKit+Methods_Sleep.m"; sourceTree = "<group>"; };
58C81E6D1F84F6970005DD48 /* RCTAppleHealthKit+Methods_Activity.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = "RCTAppleHealthKit+Methods_Activity.m"; sourceTree = "<group>"; };
58C81E6E1F84F6970005DD48 /* RCTAppleHealthKit+Methods_Activity.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "RCTAppleHealthKit+Methods_Activity.h"; sourceTree = "<group>"; };
61232F911E303758000A5026 /* RCTAppleHealthKit+Methods_Mindfulness.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "RCTAppleHealthKit+Methods_Mindfulness.h"; sourceTree = "<group>"; }; 61232F911E303758000A5026 /* RCTAppleHealthKit+Methods_Mindfulness.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "RCTAppleHealthKit+Methods_Mindfulness.h"; sourceTree = "<group>"; };
61232F921E303758000A5026 /* RCTAppleHealthKit+Methods_Mindfulness.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "RCTAppleHealthKit+Methods_Mindfulness.m"; sourceTree = "<group>"; }; 61232F921E303758000A5026 /* RCTAppleHealthKit+Methods_Mindfulness.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "RCTAppleHealthKit+Methods_Mindfulness.m"; sourceTree = "<group>"; };
64C42D481D351A8800A0A8F7 /* RCTAppleHealthKit+Methods_Vitals.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "RCTAppleHealthKit+Methods_Vitals.h"; sourceTree = "<group>"; }; 64C42D481D351A8800A0A8F7 /* RCTAppleHealthKit+Methods_Vitals.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "RCTAppleHealthKit+Methods_Vitals.h"; sourceTree = "<group>"; };
...@@ -93,6 +96,8 @@ ...@@ -93,6 +96,8 @@
3774C88F1D2092F20000B3F3 /* RCTAppleHealthKit */ = { 3774C88F1D2092F20000B3F3 /* RCTAppleHealthKit */ = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
58C81E6E1F84F6970005DD48 /* RCTAppleHealthKit+Methods_Activity.h */,
58C81E6D1F84F6970005DD48 /* RCTAppleHealthKit+Methods_Activity.m */,
61232F911E303758000A5026 /* RCTAppleHealthKit+Methods_Mindfulness.h */, 61232F911E303758000A5026 /* RCTAppleHealthKit+Methods_Mindfulness.h */,
61232F921E303758000A5026 /* RCTAppleHealthKit+Methods_Mindfulness.m */, 61232F921E303758000A5026 /* RCTAppleHealthKit+Methods_Mindfulness.m */,
64E0E73D1D37947B00EAB905 /* RCTAppleHealthKit+Methods_Results.h */, 64E0E73D1D37947B00EAB905 /* RCTAppleHealthKit+Methods_Results.h */,
...@@ -189,6 +194,7 @@ ...@@ -189,6 +194,7 @@
83C70EFC1FDFA6BB00AD7AA9 /* RCTAppleHealthKit+NSUserDefaults.m in Sources */, 83C70EFC1FDFA6BB00AD7AA9 /* RCTAppleHealthKit+NSUserDefaults.m in Sources */,
3774C89E1D2095850000B3F3 /* RCTAppleHealthKit+TypesAndPermissions.m in Sources */, 3774C89E1D2095850000B3F3 /* RCTAppleHealthKit+TypesAndPermissions.m in Sources */,
3774C8D71D20C65F0000B3F3 /* RCTAppleHealthKit+Methods_Fitness.m in Sources */, 3774C8D71D20C65F0000B3F3 /* RCTAppleHealthKit+Methods_Fitness.m in Sources */,
58C81E6F1F84F6970005DD48 /* RCTAppleHealthKit+Methods_Activity.m in Sources */,
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
}; };
......
//
// RCTAppleHealthKit+Methods_Activity.h
// RCTAppleHealthKit
//
// Created by Alexander Vallorosi on 4/27/17.
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "RCTAppleHealthKit.h"
@interface RCTAppleHealthKit (Methods_Activity)
- (void)activity_getActiveEnergyBurned:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;
- (void)activity_getBasalEnergyBurned:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;
@end
//
// RCTAppleHealthKit+Methods_Activity.m
// RCTAppleHealthKit
//
// Created by Alexander Vallorosi on 4/27/17.
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
#import "RCTAppleHealthKit+Methods_Activity.h"
#import "RCTAppleHealthKit+Queries.h"
#import "RCTAppleHealthKit+Utils.h"
@implementation RCTAppleHealthKit (Methods_Activity)
- (void)activity_getActiveEnergyBurned:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback
{
HKQuantityType *activeEnergyType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];
NSDate *startDate = [RCTAppleHealthKit dateFromOptions:input key:@"startDate" withDefault:nil];
NSDate *endDate = [RCTAppleHealthKit dateFromOptions:input key:@"endDate" withDefault:[NSDate date]];
HKUnit *cal = [HKUnit kilocalorieUnit];
if(startDate == nil){
callback(@[RCTMakeError(@"startDate is required in options", nil, nil)]);
return;
}
NSPredicate * predicate = [RCTAppleHealthKit predicateForSamplesBetweenDates:startDate endDate:endDate];
[self fetchQuantitySamplesOfType:activeEnergyType
unit:cal
predicate:predicate
ascending:false
limit:HKObjectQueryNoLimit
completion:^(NSArray *results, NSError *error) {
if(results){
callback(@[[NSNull null], results]);
return;
} else {
callback(@[RCTJSErrorFromNSError(error)]);
return;
}
}];
}
- (void)activity_getBasalEnergyBurned:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback
{
HKQuantityType *basalEnergyType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBasalEnergyBurned];
NSDate *startDate = [RCTAppleHealthKit dateFromOptions:input key:@"startDate" withDefault:nil];
NSDate *endDate = [RCTAppleHealthKit dateFromOptions:input key:@"endDate" withDefault:[NSDate date]];
HKUnit *cal = [HKUnit kilocalorieUnit];
if(startDate == nil){
callback(@[RCTMakeError(@"startDate is required in options", nil, nil)]);
return;
}
NSPredicate * predicate = [RCTAppleHealthKit predicateForSamplesBetweenDates:startDate endDate:endDate];
[self fetchQuantitySamplesOfType:basalEnergyType
unit:cal
predicate:predicate
ascending:false
limit:HKObjectQueryNoLimit
completion:^(NSArray *results, NSError *error) {
if(results){
callback(@[[NSNull null], results]);
return;
} else {
callback(@[RCTJSErrorFromNSError(error)]);
return;
}
}];
}
@end
...@@ -3,7 +3,8 @@ ...@@ -3,7 +3,8 @@
// RCTAppleHealthKit // RCTAppleHealthKit
// //
// Created by Greg Wilson on 2016-06-26. // Created by Greg Wilson on 2016-06-26.
// Copyright © 2016 Greg Wilson. All rights reserved. // This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
// //
#import "RCTAppleHealthKit.h" #import "RCTAppleHealthKit.h"
...@@ -22,6 +23,11 @@ ...@@ -22,6 +23,11 @@
- (void)body_saveHeight:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback; - (void)body_saveHeight:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;
- (void)body_getLatestBodyFatPercentage:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback; - (void)body_getLatestBodyFatPercentage:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;
- (void)body_getBodyFatPercentageSamples:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;
- (void)body_saveBodyFatPercentage:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;
- (void)body_getLatestLeanBodyMass:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback; - (void)body_getLatestLeanBodyMass:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;
- (void)body_getLeanBodyMassSamples:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;
- (void)body_saveLeanBodyMass:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;
@end @end
...@@ -3,7 +3,8 @@ ...@@ -3,7 +3,8 @@
// RCTAppleHealthKit // RCTAppleHealthKit
// //
// Created by Greg Wilson on 2016-06-29. // Created by Greg Wilson on 2016-06-29.
// Copyright © 2016 Greg Wilson. All rights reserved. // This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
// //
#import "RCTAppleHealthKit.h" #import "RCTAppleHealthKit.h"
......
...@@ -3,7 +3,8 @@ ...@@ -3,7 +3,8 @@
// RCTAppleHealthKit // RCTAppleHealthKit
// //
// Created by Greg Wilson on 2016-06-29. // Created by Greg Wilson on 2016-06-29.
// Copyright © 2016 Greg Wilson. All rights reserved. // This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
// //
#import "RCTAppleHealthKit+Methods_Characteristic.h" #import "RCTAppleHealthKit+Methods_Characteristic.h"
...@@ -33,8 +34,7 @@ ...@@ -33,8 +34,7 @@
} }
if(value == nil){ if(value == nil){
NSLog(@"error getting biological sex: %@", error); callback(@[RCTJSErrorFromNSError(error)]);
callback(@[RCTMakeError(@"error getting biological sex", error, nil)]);
return; return;
} }
...@@ -51,8 +51,7 @@ ...@@ -51,8 +51,7 @@
NSDate *dob = [self.healthStore dateOfBirthWithError:&error]; NSDate *dob = [self.healthStore dateOfBirthWithError:&error];
if(error != nil){ if(error != nil){
NSLog(@"error getting date of birth: %@", error); callback(@[RCTJSErrorFromNSError(error)]);
callback(@[RCTMakeError(@"error getting date of birth", error, nil)]);
return; return;
} }
if(dob == nil) { if(dob == nil) {
......
//
// RCTAppleHealthKit+Methods_Dietary.h
// RCTAppleHealthKit
//
// Created by Greg Wilson on 2016-06-26.
// Copyright © 2016 Greg Wilson. All rights reserved.
//
#import "RCTAppleHealthKit.h"
@interface RCTAppleHealthKit (Methods_Dietary)
- (void)saveFood:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;
- (void)saveWater:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;
@end
This diff is collapsed.
...@@ -3,7 +3,8 @@ ...@@ -3,7 +3,8 @@
// RCTAppleHealthKit // RCTAppleHealthKit
// //
// Created by Greg Wilson on 2016-06-26. // Created by Greg Wilson on 2016-06-26.
// Copyright © 2016 Greg Wilson. All rights reserved. // This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
// //
#import "RCTAppleHealthKit.h" #import "RCTAppleHealthKit.h"
...@@ -13,11 +14,17 @@ ...@@ -13,11 +14,17 @@
- (void)fitness_getStepCountOnDay:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback; - (void)fitness_getStepCountOnDay:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;
- (void)fitness_geStepSamples:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback; - (void)fitness_geStepSamples:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;
- (void)fitness_geStepSamplesByAnchor:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback; - (void)fitness_geStepSamplesByAnchor:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;
- (void)fitness_getSamples:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;
- (void)fitness_setObserver:(NSDictionary *)input;
- (void)fitness_getDailyStepSamples:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback; - (void)fitness_getDailyStepSamples:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;
- (void)fitness_saveSteps:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback; - (void)fitness_saveSteps:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;
- (void)fitness_initializeStepEventObserver:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback; - (void)fitness_initializeStepEventObserver:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;
- (void)fitness_getDistanceWalkingRunningOnDay:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback; - (void)fitness_getDistanceWalkingRunningOnDay:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;
- (void)fitness_getDailyDistanceWalkingRunningSamples:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;
- (void)fitness_getDailyDistanceSwimmingSamples:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;
- (void)fitness_getDistanceCyclingOnDay:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback; - (void)fitness_getDistanceCyclingOnDay:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;
- (void)fitness_getDailyDistanceCyclingSamples:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;
- (void)fitness_getFlightsClimbedOnDay:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback; - (void)fitness_getFlightsClimbedOnDay:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;
- (void)fitness_getDailyFlightsClimbedSamples:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;
@end @end
...@@ -29,8 +29,7 @@ ...@@ -29,8 +29,7 @@
[self.healthStore saveObject:sample withCompletion:^(BOOL success, NSError *error) { [self.healthStore saveObject:sample withCompletion:^(BOOL success, NSError *error) {
if (!success) { if (!success) {
NSLog(@"An error occured saving the mindful session sample %@. The error was: %@.", sample, error); callback(@[RCTJSErrorFromNSError(error)]);
callback(@[RCTMakeError(@"An error occured saving the mindful session sample", error, nil)]);
return; return;
} }
callback(@[[NSNull null], @(value)]); callback(@[[NSNull null], @(value)]);
......
...@@ -32,8 +32,7 @@ ...@@ -32,8 +32,7 @@
callback(@[[NSNull null], results]); callback(@[[NSNull null], results]);
return; return;
} else { } else {
NSLog(@"error getting blood glucose samples: %@", error); callback(@[RCTJSErrorFromNSError(error)]);
callback(@[RCTMakeError(@"error getting blood glucose samples", nil, nil)]);
return; return;
} }
}]; }];
......
...@@ -3,7 +3,8 @@ ...@@ -3,7 +3,8 @@
// RCTAppleHealthKit // RCTAppleHealthKit
// //
// Created by Greg Wilson on 2016-11-06. // Created by Greg Wilson on 2016-11-06.
// Copyright © 2016 Greg Wilson. All rights reserved. // This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
// //
#import "RCTAppleHealthKit.h" #import "RCTAppleHealthKit.h"
......
...@@ -3,7 +3,8 @@ ...@@ -3,7 +3,8 @@
// RCTAppleHealthKit // RCTAppleHealthKit
// //
// Created by Greg Wilson on 2016-11-06. // Created by Greg Wilson on 2016-11-06.
// Copyright © 2016 Greg Wilson. All rights reserved. // This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
// //
...@@ -35,8 +36,7 @@ ...@@ -35,8 +36,7 @@
callback(@[[NSNull null], results]); callback(@[[NSNull null], results]);
return; return;
} else { } else {
NSLog(@"error getting sleep samples: %@", error); callback(@[RCTJSErrorFromNSError(error)]);
callback(@[RCTMakeError(@"error getting sleep samples", nil, nil)]);
return; return;
} }
}]; }];
......
...@@ -33,8 +33,7 @@ ...@@ -33,8 +33,7 @@
callback(@[[NSNull null], results]); callback(@[[NSNull null], results]);
return; return;
} else { } else {
NSLog(@"error getting heart rate samples: %@", error); callback(@[RCTJSErrorFromNSError(error)]);
callback(@[RCTMakeError(@"error getting heart rate samples", nil, nil)]);
return; return;
} }
}]; }];
......
...@@ -3,7 +3,8 @@ ...@@ -3,7 +3,8 @@
// RCTAppleHealthKit // RCTAppleHealthKit
// //
// Created by Greg Wilson on 2016-06-26. // Created by Greg Wilson on 2016-06-26.
// Copyright © 2016 Greg Wilson. All rights reserved. // This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
// //
#import "RCTAppleHealthKit.h" #import "RCTAppleHealthKit.h"
...@@ -18,6 +19,18 @@ ...@@ -18,6 +19,18 @@
startDate:(NSDate *)startDate startDate:(NSDate *)startDate
endDate:(NSDate *)endDate endDate:(NSDate *)endDate
completion:(void (^)(NSArray *, NSError *))completionHandler; completion:(void (^)(NSArray *, NSError *))completionHandler;
- (void)fetchSamplesOfType:(HKSampleType *)quantityType
unit:(HKUnit *)unit
predicate:(NSPredicate *)predicate
ascending:(BOOL)asc
limit:(NSUInteger)lim
completion:(void (^)(NSArray *, NSError *))completion;
- (void)setObserverForType:(HKSampleType *)quantityType
unit:(HKUnit *)unit;
- (void)fetchQuantitySamplesOfType:(HKQuantityType *)quantityType - (void)fetchQuantitySamplesOfType:(HKQuantityType *)quantityType
unit:(HKUnit *)unit unit:(HKUnit *)unit
predicate:(NSPredicate *)predicate predicate:(NSPredicate *)predicate
...@@ -43,8 +56,24 @@ ...@@ -43,8 +56,24 @@
ascending:(BOOL)asc ascending:(BOOL)asc
limit:(NSUInteger)lim limit:(NSUInteger)lim
gap:(NSString *)gap gap:(NSString *)gap
includeManuallyAdded:(BOOL)includeManuallyAdded
completion:(void (^)(NSArray *, NSError *))completionHandler;
- (void)fetchCumulativeSumStatisticsCollection:(HKQuantityType *)quantityType
unit:(HKUnit *)unit
startDate:(NSDate *)startDate
endDate:(NSDate *)endDate
ascending:(BOOL)asc
limit:(NSUInteger)lim
completion:(void (^)(NSArray *, NSError *))completionHandler;
- (void)fetchCumulativeSumStatisticsCollection:(HKQuantityType *)quantityType
unit:(HKUnit *)unit
period:(NSUInteger)period
startDate:(NSDate *)startDate
endDate:(NSDate *)endDate
ascending:(BOOL)asc
limit:(NSUInteger)lim
includeManuallyAdded:(BOOL)includeManuallyAdded
completion:(void (^)(NSArray *, NSError *))completionHandler; completion:(void (^)(NSArray *, NSError *))completionHandler;
- (void)fetchSleepCategorySamplesForPredicate:(NSPredicate *)predicate - (void)fetchSleepCategorySamplesForPredicate:(NSPredicate *)predicate
......
...@@ -3,14 +3,19 @@ ...@@ -3,14 +3,19 @@
// RCTAppleHealthKit // RCTAppleHealthKit
// //
// Created by Greg Wilson on 2016-06-26. // Created by Greg Wilson on 2016-06-26.
// Copyright © 2016 Greg Wilson. All rights reserved. // This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
// //
#import "RCTAppleHealthKit.h" #import "RCTAppleHealthKit.h"
@interface RCTAppleHealthKit (TypesAndPermissions) @interface RCTAppleHealthKit (TypesAndPermissions)
- (NSDictionary *)readPermsDict;
- (NSDictionary *)writePermsDict;
- (NSSet *)getReadPermsFromOptions:(NSArray *)options; - (NSSet *)getReadPermsFromOptions:(NSArray *)options;
- (NSSet *)getWritePermsFromOptions:(NSArray *)options; - (NSSet *)getWritePermsFromOptions:(NSArray *)options;
- (HKObjectType *)getWritePermFromString:(NSString *)string;
- (NSString *)getAuthorizationStatusString:(HKAuthorizationStatus)status;
@end @end
...@@ -3,7 +3,8 @@ ...@@ -3,7 +3,8 @@
// RCTAppleHealthKit // RCTAppleHealthKit
// //
// Created by Greg Wilson on 2016-06-26. // Created by Greg Wilson on 2016-06-26.
// Copyright © 2016 Greg Wilson. All rights reserved. // This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
// //
#import "RCTAppleHealthKit+TypesAndPermissions.h" #import "RCTAppleHealthKit+TypesAndPermissions.h"
...@@ -30,6 +31,7 @@ ...@@ -30,6 +31,7 @@
@"StepCount" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount], @"StepCount" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount],
@"DistanceWalkingRunning" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning], @"DistanceWalkingRunning" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning],
@"DistanceCycling" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceCycling], @"DistanceCycling" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceCycling],
@"DistanceSwimming" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceSwimming],
@"BasalEnergyBurned" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBasalEnergyBurned], @"BasalEnergyBurned" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBasalEnergyBurned],
@"ActiveEnergyBurned" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned], @"ActiveEnergyBurned" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned],
@"FlightsClimbed" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierFlightsClimbed], @"FlightsClimbed" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierFlightsClimbed],
...@@ -49,6 +51,8 @@ ...@@ -49,6 +51,8 @@
@"SleepAnalysis" : [HKObjectType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis], @"SleepAnalysis" : [HKObjectType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis],
// Mindfulness // Mindfulness
@"MindfulSession" : [HKObjectType categoryTypeForIdentifier:HKCategoryTypeIdentifierMindfulSession], @"MindfulSession" : [HKObjectType categoryTypeForIdentifier:HKCategoryTypeIdentifierMindfulSession],
//workouts
@"Workout" : [HKObjectType workoutType],
}; };
return readPerms; return readPerms;
} }
...@@ -72,7 +76,44 @@ ...@@ -72,7 +76,44 @@
@"ActiveEnergyBurned" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned], @"ActiveEnergyBurned" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned],
@"FlightsClimbed" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierFlightsClimbed], @"FlightsClimbed" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierFlightsClimbed],
// Nutrition Identifiers // Nutrition Identifiers
@"DietaryEnergy" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryEnergyConsumed], @"Biotin" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryBiotin],
@"Caffeine" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryCaffeine],
@"Calcium" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryCalcium],
@"Carbohydrates" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryCarbohydrates],
@"Chloride" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryChloride],
@"Cholesterol" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryCholesterol],
@"Copper" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryCopper],
@"EnergyConsumed" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryEnergyConsumed],
@"FatMonounsaturated" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryFatMonounsaturated],
@"FatPolyunsaturated" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryFatPolyunsaturated],
@"FatSaturated" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryFatSaturated],
@"FatTotal" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryFatTotal],
@"Fiber" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryFiber],
@"Folate" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryFolate],
@"Iodine" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryIodine],
@"Iron" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryIron],
@"Magnesium" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryMagnesium],
@"Manganese" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryManganese],
@"Molybdenum" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryMolybdenum],
@"Niacin" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryNiacin],
@"PantothenicAcid" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryPantothenicAcid],
@"Phosphorus" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryPhosphorus],
@"Potassium" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryPotassium],
@"Protein" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryProtein],
@"Riboflavin" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryRiboflavin],
@"Selenium" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietarySelenium],
@"Sodium" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietarySodium],
@"Sugar" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietarySugar],
@"Thiamin" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryThiamin],
@"VitaminA" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryVitaminA],
@"VitaminB12" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryVitaminB12],
@"VitaminB6" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryVitaminB6],
@"VitaminC" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryVitaminC],
@"VitaminD" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryVitaminD],
@"VitaminE" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryVitaminE],
@"VitaminK" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryVitaminK],
@"Zinc" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryZinc],
@"Water" : [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryWater],
// Sleep // Sleep
@"SleepAnalysis" : [HKObjectType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis], @"SleepAnalysis" : [HKObjectType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis],
// Mindfulness // Mindfulness
...@@ -81,7 +122,6 @@ ...@@ -81,7 +122,6 @@
return writePerms; return writePerms;
} }
// Returns HealthKit read permissions from options array // Returns HealthKit read permissions from options array
- (NSSet *)getReadPermsFromOptions:(NSArray *)options { - (NSSet *)getReadPermsFromOptions:(NSArray *)options {
NSDictionary *readPermDict = [self readPermsDict]; NSDictionary *readPermDict = [self readPermsDict];
...@@ -113,4 +153,18 @@ ...@@ -113,4 +153,18 @@
return writePermSet; return writePermSet;
} }
- (HKObjectType *)getWritePermFromString:(NSString *)writePerm {
return [[self writePermsDict] objectForKey:writePerm];
}
- (NSString *)getAuthorizationStatusString:(HKAuthorizationStatus)status {
switch (status) {
case HKAuthorizationStatusNotDetermined:
return @"NotDetermined";
case HKAuthorizationStatusSharingDenied:
return @"SharingDenied";
case HKAuthorizationStatusSharingAuthorized:
return @"SharingAuthorized";
}
}
@end @end
...@@ -3,7 +3,8 @@ ...@@ -3,7 +3,8 @@
// RCTAppleHealthKit // RCTAppleHealthKit
// //
// Created by Greg Wilson on 2016-06-26. // Created by Greg Wilson on 2016-06-26.
// Copyright © 2016 Greg Wilson. All rights reserved. // This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
// //
#import "RCTAppleHealthKit.h" #import "RCTAppleHealthKit.h"
...@@ -23,7 +24,7 @@ ...@@ -23,7 +24,7 @@
+ (NSDate *)startDateFromOptions:(NSDictionary *)options; + (NSDate *)startDateFromOptions:(NSDictionary *)options;
+ (NSDate *)endDateFromOptions:(NSDictionary *)options; + (NSDate *)endDateFromOptions:(NSDictionary *)options;
+ (NSDate *)endDateFromOptionsDefaultNow:(NSDictionary *)options; + (NSDate *)endDateFromOptionsDefaultNow:(NSDictionary *)options;
+ (HKUnit *)hkUnitFromOptions:(NSDictionary *)options; + (HKSampleType *)hkQuantityTypeFromString:(NSString *)type;
+ (HKUnit *)hkUnitFromOptions:(NSDictionary *)options key:(NSString *)key withDefault:(HKUnit *)defaultValue; + (HKUnit *)hkUnitFromOptions:(NSDictionary *)options key:(NSString *)key withDefault:(HKUnit *)defaultValue;
+ (NSUInteger)uintFromOptions:(NSDictionary *)options key:(NSString *)key withDefault:(NSUInteger)defaultValue; + (NSUInteger)uintFromOptions:(NSDictionary *)options key:(NSString *)key withDefault:(NSUInteger)defaultValue;
...@@ -33,6 +34,7 @@ ...@@ -33,6 +34,7 @@
+ (bool)boolFromOptions:(NSDictionary *)options key:(NSString *)key withDefault:(bool)defaultValue; + (bool)boolFromOptions:(NSDictionary *)options key:(NSString *)key withDefault:(bool)defaultValue;
+ (NSMutableArray *)reverseNSMutableArray:(NSMutableArray *)array; + (NSMutableArray *)reverseNSMutableArray:(NSMutableArray *)array;
+ (NSString*) stringForHKWorkoutActivityType:(int) enumValue;
+ (NSString *)stringFromType:(HKSampleType *)type status:(bool)status; + (NSString *)stringFromType:(HKSampleType *)type status:(bool)status;
......
This diff is collapsed.
...@@ -3,7 +3,8 @@ ...@@ -3,7 +3,8 @@
// RCTAppleHealthKit // RCTAppleHealthKit
// //
// Created by Greg Wilson on 2016-06-26. // Created by Greg Wilson on 2016-06-26.
// Copyright © 2016 Greg Wilson. All rights reserved. // This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
// //
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
...@@ -15,9 +16,11 @@ ...@@ -15,9 +16,11 @@
@interface RCTAppleHealthKit : NSObject <RCTBridgeModule> @interface RCTAppleHealthKit : NSObject <RCTBridgeModule>
@property (nonatomic) HKHealthStore *healthStore; @property (nonatomic) HKHealthStore *healthStore;
@property BOOL isSync;
- (void)isHealthKitAvailable:(RCTResponseSenderBlock)callback; - (void)isHealthKitAvailable:(RCTResponseSenderBlock)callback;
- (void)initializeHealthKit:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback; - (void)initializeHealthKit:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;
- (void)checkPermission:(NSString *)input callback:(RCTResponseSenderBlock)callback;
- (void)getModuleInfo:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback; - (void)getModuleInfo:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;
@end @end
...@@ -3,14 +3,17 @@ ...@@ -3,14 +3,17 @@
// RCTAppleHealthKit // RCTAppleHealthKit
// //
// Created by Greg Wilson on 2016-06-26. // Created by Greg Wilson on 2016-06-26.
// Copyright © 2016 Greg Wilson. All rights reserved. // This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
// //
#import "RCTAppleHealthKit.h" #import "RCTAppleHealthKit.h"
#import "RCTAppleHealthKit+TypesAndPermissions.h" #import "RCTAppleHealthKit+TypesAndPermissions.h"
#import "RCTAppleHealthKit+Methods_Activity.h"
#import "RCTAppleHealthKit+Methods_Body.h" #import "RCTAppleHealthKit+Methods_Body.h"
#import "RCTAppleHealthKit+Methods_Fitness.h" #import "RCTAppleHealthKit+Methods_Fitness.h"
#import "RCTAppleHealthKit+Methods_Dietary.h"
#import "RCTAppleHealthKit+Methods_Characteristic.h" #import "RCTAppleHealthKit+Methods_Characteristic.h"
#import "RCTAppleHealthKit+Methods_Vitals.h" #import "RCTAppleHealthKit+Methods_Vitals.h"
#import "RCTAppleHealthKit+Methods_Results.h" #import "RCTAppleHealthKit+Methods_Results.h"
...@@ -22,6 +25,7 @@ ...@@ -22,6 +25,7 @@
#import <React/RCTEventDispatcher.h> #import <React/RCTEventDispatcher.h>
@implementation RCTAppleHealthKit @implementation RCTAppleHealthKit
@synthesize bridge = _bridge; @synthesize bridge = _bridge;
RCT_EXPORT_MODULE(); RCT_EXPORT_MODULE();
...@@ -96,11 +100,31 @@ RCT_EXPORT_METHOD(getLatestBodyFatPercentage:(NSDictionary *)input callback:(RCT ...@@ -96,11 +100,31 @@ RCT_EXPORT_METHOD(getLatestBodyFatPercentage:(NSDictionary *)input callback:(RCT
[self body_getLatestBodyFatPercentage:input callback:callback]; [self body_getLatestBodyFatPercentage:input callback:callback];
} }
RCT_EXPORT_METHOD(getBodyFatPercentageSamples:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback)
{
[self body_getBodyFatPercentageSamples:input callback:callback];
}
RCT_EXPORT_METHOD(saveBodyFatPercentage:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback)
{
[self body_saveBodyFatPercentage:input callback:callback];
}
RCT_EXPORT_METHOD(getLatestLeanBodyMass:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback) RCT_EXPORT_METHOD(getLatestLeanBodyMass:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback)
{ {
[self body_getLatestLeanBodyMass:input callback:callback]; [self body_getLatestLeanBodyMass:input callback:callback];
} }
RCT_EXPORT_METHOD(getLeanBodyMassSamples:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback)
{
[self body_getLeanBodyMassSamples:input callback:callback];
}
RCT_EXPORT_METHOD(saveLeanBodyMass:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback)
{
[self body_saveLeanBodyMass:input callback:callback];
}
RCT_EXPORT_METHOD(getStepCount:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback) RCT_EXPORT_METHOD(getStepCount:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback)
{ {
[self fitness_getStepCountOnDay:input callback:callback]; [self fitness_getStepCountOnDay:input callback:callback];
...@@ -116,6 +140,17 @@ RCT_EXPORT_METHOD(getStepCountSamplesByAnchor:(NSDictionary *)input callback:(RC ...@@ -116,6 +140,17 @@ RCT_EXPORT_METHOD(getStepCountSamplesByAnchor:(NSDictionary *)input callback:(RC
[self fitness_geStepSamplesByAnchor:input callback:callback]; [self fitness_geStepSamplesByAnchor:input callback:callback];
} }
RCT_EXPORT_METHOD(getSamples:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback)
{
[self fitness_getSamples:input callback:callback];
}
RCT_EXPORT_METHOD(setObserver:(NSDictionary *)input)
{
[self fitness_setObserver:input];
}
RCT_EXPORT_METHOD(getDailyStepCountSamples:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback) RCT_EXPORT_METHOD(getDailyStepCountSamples:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback)
{ {
[self fitness_getDailyStepSamples:input callback:callback]; [self fitness_getDailyStepSamples:input callback:callback];
...@@ -131,16 +166,46 @@ RCT_EXPORT_METHOD(getDistanceWalkingRunning:(NSDictionary *)input callback:(RCTR ...@@ -131,16 +166,46 @@ RCT_EXPORT_METHOD(getDistanceWalkingRunning:(NSDictionary *)input callback:(RCTR
[self fitness_getDistanceWalkingRunningOnDay:input callback:callback]; [self fitness_getDistanceWalkingRunningOnDay:input callback:callback];
} }
RCT_EXPORT_METHOD(getDailyDistanceWalkingRunningSamples:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback)
{
[self fitness_getDailyDistanceWalkingRunningSamples:input callback:callback];
}
RCT_EXPORT_METHOD(getDailyDistanceSwimmingSamples:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback)
{
[self fitness_getDailyDistanceSwimmingSamples:input callback:callback];
}
RCT_EXPORT_METHOD(getDistanceCycling:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback) RCT_EXPORT_METHOD(getDistanceCycling:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback)
{ {
[self fitness_getDistanceCyclingOnDay:input callback:callback]; [self fitness_getDistanceCyclingOnDay:input callback:callback];
} }
RCT_EXPORT_METHOD(getDailyDistanceCyclingSamples:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback)
{
[self fitness_getDailyDistanceCyclingSamples:input callback:callback];
}
RCT_EXPORT_METHOD(getFlightsClimbed:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback) RCT_EXPORT_METHOD(getFlightsClimbed:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback)
{ {
[self fitness_getFlightsClimbedOnDay:input callback:callback]; [self fitness_getFlightsClimbedOnDay:input callback:callback];
} }
RCT_EXPORT_METHOD(getDailyFlightsClimbedSamples:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback)
{
[self fitness_getDailyFlightsClimbedSamples:input callback:callback];
}
RCT_EXPORT_METHOD(saveFood:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback)
{
[self saveFood:input callback:callback];
}
RCT_EXPORT_METHOD(saveWater:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback)
{
[self saveWater:input callback:callback];
}
RCT_EXPORT_METHOD(getHeartRateSamples:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback) RCT_EXPORT_METHOD(getHeartRateSamples:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback)
{ {
[self vitals_getHeartRateSamples:input callback:callback]; [self vitals_getHeartRateSamples:input callback:callback];
...@@ -151,6 +216,16 @@ RCT_EXPORT_METHOD(getHeartRateSamplesByAnchor:(NSDictionary *)input callback:(RC ...@@ -151,6 +216,16 @@ RCT_EXPORT_METHOD(getHeartRateSamplesByAnchor:(NSDictionary *)input callback:(RC
[self vitals_getHeartRateSamplesByAnchor:input callback:callback]; [self vitals_getHeartRateSamplesByAnchor:input callback:callback];
} }
RCT_EXPORT_METHOD(getActiveEnergyBurned:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback)
{
[self activity_getActiveEnergyBurned:input callback:callback];
}
RCT_EXPORT_METHOD(getBasalEnergyBurned:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback)
{
[self activity_getBasalEnergyBurned:input callback:callback];
}
RCT_EXPORT_METHOD(getBodyTemperatureSamples:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback) RCT_EXPORT_METHOD(getBodyTemperatureSamples:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback)
{ {
[self vitals_getBodyTemperatureSamples:input callback:callback]; [self vitals_getBodyTemperatureSamples:input callback:callback];
...@@ -261,9 +336,7 @@ RCT_EXPORT_METHOD(setTimestamp:(NSDictionary *)input callback:(RCTResponseSender ...@@ -261,9 +336,7 @@ RCT_EXPORT_METHOD(setTimestamp:(NSDictionary *)input callback:(RCTResponseSender
[self.healthStore requestAuthorizationToShareTypes:writeDataTypes readTypes:readDataTypes completion:^(BOOL success, NSError *error) { [self.healthStore requestAuthorizationToShareTypes:writeDataTypes readTypes:readDataTypes completion:^(BOOL success, NSError *error) {
if (!success) { if (!success) {
NSString *errMsg = [NSString stringWithFormat:@"Error with HealthKit authorization: %@", error]; callback(@[RCTJSErrorFromNSError(error)]);
NSLog(errMsg);
callback(@[RCTMakeError(errMsg, nil, nil)]);
return; return;
} else { } else {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
...@@ -276,6 +349,28 @@ RCT_EXPORT_METHOD(setTimestamp:(NSDictionary *)input callback:(RCTResponseSender ...@@ -276,6 +349,28 @@ RCT_EXPORT_METHOD(setTimestamp:(NSDictionary *)input callback:(RCTResponseSender
} }
} }
RCT_EXPORT_METHOD(authorizationStatusForType:(NSString *)type
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject
{
if (self.healthStore == nil) {
self.healthStore = [[HKHealthStore alloc] init];
}
if ([HKHealthStore isHealthDataAvailable]) {
HKObjectType *objectType = [self getWritePermFromString:type];
if (objectType == nil) {
reject(@"unknown write permission", nil, nil);
return;
}
NSString *status = [self getAuthorizationStatusString:[self.healthStore authorizationStatusForType:objectType]];
resolve(status);
} else {
reject(@"HealthKit data is not available", nil, nil);
}
})
- (void)getModuleInfo:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback - (void)getModuleInfo:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback
{ {
NSDictionary *info = @{ NSDictionary *info = @{
......
This diff is collapsed.
Install the `rn-apple-healthkit` npm package
- Run `npm install rn-apple-healthkit --save`
- Run `react-native link rn-apple-healthkit`
Update `info.plist` in your React Native project
```
<key>NSHealthShareUsageDescription</key>
<string>Read and understand health data.</string>
<key>NSHealthUpdateUsageDescription</key>
<string>Share workout data with other apps.</string>
```
These permissions are exported as constants of the `rn-apple-healthkit` module.
```javascript
import AppleHealthKit from 'rn-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
],
}
};
```
\ No newline at end of file
Check the authorization status for sharing (writing) the specified data type.
Status will be one of `"NotDetermined"`, `"SharingDenied"`, `"SharingAuthorized"`.
```javascript
try {
const status = await AppleHealthKit.authorizationStatusForType("StepCount")
if (status) {
console.log("status is", status)
}
} catch (error) {
console.warn(error)
}
```
There is no way to check authorization status for read permission, [see this](https://developer.apple.com/documentation/healthkit/hkhealthstore/1614154-authorizationstatusfortype?language=objc).
A quantity sample type that measures the amount of active energy the user has burned.
```javascript
let d = new Date(2016,1,1);
let options = {
startDate: (new Date(2016,10,1)).toISOString(), // required
endDate: (new Date()).toISOString(), // optional; default now
};
```
```javascript
AppleHealthKit.getActiveEnergyBurned(options: Object, (err: Object, results: Object) => {
if (err) {
return;
}
console.log(results)
});
```
\ No newline at end of file
```javascript
let d = new Date(2016,1,1);
let options = {
startDate: (new Date(2018,10,1)).toISOString(), // required
endDate: (new Date()).toISOString(), // optional; default now
};
```
```javascript
AppleHealthKit.getBasalEnergyBurned(options: Object, (err: Object, results: Object) => {
if (err) {
return;
}
console.log(results)
});
```
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 |
```javascript
AppleHealthKit.getBiologicalSex(null, (err: Object, results: Object) => {
if (this._handleHealthkitError(err, 'getBiologicalSex')) {
return;
}
console.log(results)
});
```
```javascript
{
value: 'female',
}
```
\ No newline at end of file
Query for blood glucose samples. the options object is used to setup a query to retrieve relevant samples.
```javascript
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*, *sourceId*, *sourceName*, *startDate*, and *endDate* fields
```javascript
AppleHealthKit.getBloodGlucoseSamples(options, (err: Object, results: Array<Object>) => {
if (err) {
return;
}
console.log(results)
});
```
Query for blood pressure samples. the options object is used to setup a query to retrieve relevant samples.
```javascript
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
```javascript
AppleHealthKit.getBloodPressureSamples(options, (err: Object, results: Array<Object>) => {
if (err) {
return;
}
console.log(results)
});
```
```javascript
[
{ 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' },
]
```
\ No newline at end of file
Query for body fat percentage samples. the options object is used to setup a query to retrieve relevant samples.
```javascript
let options = {
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
};
```
```javascript
AppleHealthKit.getBodyFatPercentageSamples(options, (err: Object, results: Array<Object>) => {
if (err) {
return;
}
console.log(results)
});
```
```javascript
[
{ value: 16.5, startDate: '2016-07-09T00:00:00.000-0400', endDate: '2016-07-10T00:00:00.000-0400' },
{ value: 16.1, startDate: '2016-07-08T00:00:00.000-0400', endDate: '2016-07-09T00:00:00.000-0400' },
{ value: 15.9, startDate: '2016-07-07T00:00:00.000-0400', endDate: '2016-07-08T00:00:00.000-0400' },
]
```
Query for body temperature samples. the options object is used to setup a query to retrieve relevant samples.
```javascript
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.
```javascript
AppleHealthKit.getBodyTemperatureSamples(options, (err: Object, results: Array<Object>) => {
if (err) {
return;
}
console.log(results)
});
```
```javascript
[
{ 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' },
]
```
\ No newline at end of file
```javascript
let options = {
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
};
```
```javascript
AppleHealthKit.getDailyDistanceCyclingSamples(options, (err: Object, results: Array<Object>) => {
if (err) {
return;
}
console.log(results)
});
```
```javascript
let options = {
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
period: 60, // time interval in minutes optional: default 60
includeManuallyAdded: false. // optional: default false
};
```
```javascript
AppleHealthKit.getDailyDistanceSwimmingSamples(options, (err: Object, results: Array<Object>) => {
if (err) {
return;
}
console.log(results)
});
```
```javascript
let options = {
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
};
```
```javascript
AppleHealthKit.getDailyDistanceWalkingRunningSamples(options, (err: Object, results: Array<Object>) => {
if (err) {
return;
}
console.log(results)
});
```
```javascript
let options = {
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
};
```
```javascript
AppleHealthKit.getDailyFlightsClimbedSamples(options, (err: Object, results: Array<Object>) => {
if (err) {
return;
}
console.log(results)
});
```
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
```javascript
let options = {
startDate: (new Date(2016,1,1)).toISOString() // required
endDate: (new Date()).toISOString() // optional; default now
};
```
```javascript
AppleHealthKit.getDailyStepCountSamples(options: Object, (err: Object, results: Array<Object>) => {
if (this._handleHealthkitError(err, 'getDailyStepCountSamples')) {
return;
}
console.log(results)
});
```
\ No newline at end of file
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):
```javascript
AppleHealthKit.getDateOfBirth(null, (err: Object, results: Object) => {
if (this._handleHealthkitError(err, 'getDateOfBirth')) {
return;
}
console.log(results)
});
```
```javascript
{
value: '1986-09-01T00:00:00.000-0400',
age: 29
}
```
\ No newline at end of file
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`
```javascript
let options = {
unit: 'mile', // optional; default 'meter'
date: (new Date(2016,5,1)).toISOString(), // optional; default now
};
```
```javascript
AppleHealthKit.getDistanceCycling(options: Object, (err: Object, results: Object) => {
if (err) {
return;
}
console.log(results)
});
```
```javascript
{
value: 11.45,
startDate: '2016-07-08T12:00:00.000-0400',
endDate: '2016-07-08T12:00:00.000-0400'
}
```
\ No newline at end of file
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`.
```javascript
let options = {
unit: 'mile', // optional; default 'meter'
date: (new Date(2016,5,1)).toISOString(), // optional; default now
};
```
```javascript
AppleHealthKit.getDistanceWalkingRunning(options: Object, (err: Object, results: Object) => {
if (err) {
return;
}
console.log(results)
});
```
```javascript
{
value: 1.45,
startDate: '2016-07-08T12:00:00.000-0400',
endDate: '2016-07-08T12:00:00.000-0400'
}
```
\ No newline at end of file
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.
```javascript
let options = {
date: (new Date(2016,5,1)).toISOString(), // optional; default now
};
```
```javascript
AppleHealthKit.getFlightsClimbed(options: Object, (err: Object, results: Object) => {
if (err) {
return;
}
console.log(results)
});
```
```javascript
{
value: 15,
startDate: '2016-07-08T12:00:00.000-0400',
endDate: '2016-07-08T12:00:00.000-0400'
}
```
\ No newline at end of file
Query for heart rate samples. the options object is used to setup a query to retrieve relevant samples.
```javascript
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
```javascript
AppleHealthKit.getHeartRateSamples(options, (err: Object, results: Array<Object>) => {
if (err) {
return;
}
console.log(results)
});
```
```javascript
[
{ 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' },
]
\ No newline at end of file
query for height samples. the options object is used to setup a query to retrieve relevant samples.
```javascript
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
};
```
```javascript
AppleHealthKit.getHeightSamples(options, (err: Object, results: Array<Object>) => {
if (err) {
return;
}
console.log(results)
});
```
The callback function will be called with a `samples` array containing objects with `value`, `startDate`, and `endDate` fields
```javascript
[
{ 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' },
]
```
\ No newline at end of file
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.*
```javascript
AppleHealthKit.getLatestBmi(null, (err: string, results: Object) => {
if (err) {
console.log("error getting latest bmi data: ", err);
return;
}
console.log(results)
});
```
```javascript
{
value: 27.2,
startDate: '2016-07-08T12:00:00.000-0400',
endDate: '2016-07-08T12:00:00.000-0400'
}
```
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.*
```javascript
AppleHealthKit.getLatestBodyFatPercentage(null, (err: Object, results: Object) => {
if (err) {
return;
}
console.log(results)
});
```
```javascript
{
value: 20,
startDate: '2016-07-08T12:00:00.000-0400',
endDate: '2016-07-08T12:00:00.000-0400'
}
```
\ No newline at end of file
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.*
```javascript
AppleHealthKit.getLatestHeight(null, (err: string, results: Object) => {
if (err) {
console.log("error getting latest height: ", err);
return;
}
console.log(results)
});
```
```javascript
{
value: 72,
startDate: '2016-07-08T12:00:00.000-0400',
endDate: '2016-07-08T12:00:00.000-0400'
}
```
\ No newline at end of file
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.*
```javascript
AppleHealthKit.getLatestLeanBodyMass(null, (err: Object, results: Object) => {
if (err) {
return;
}
console.log(results)
});
```
```javascript
{
value: 176,
startDate: '2016-07-08T12:00:00.000-0400',
endDate: '2016-07-08T12:00:00.000-0400'
}
```
\ No newline at end of file
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.*
```javascript
let options = {
unit: 'pound'
};
```
```javascript
AppleHealthKit.getLatestWeight(options, (err: string, results: Object) => {
if (err) {
console.log("error getting latest weight: ", err);
return;
}
console.log(results)
});
```
```javascript
{
value: 200,
startDate: '2016-07-08T12:00:00.000-0400',
endDate: '2016-07-08T12:00:00.000-0400'
}
```
Query for lean body mass samples. the options object is used to setup a query to retrieve relevant samples.
```javascript
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
};
```
```javascript
AppleHealthKit.getLeanBodyMassSamples(options, (err: Object, results: Array<Object>) => {
if (err) {
return;
}
console.log(results)
});
```
```javascript
[
{ value: 160, startDate: '2016-07-09T00:00:00.000-0400', endDate: '2016-07-10T00:00:00.000-0400' },
{ value: 161, startDate: '2016-07-08T00:00:00.000-0400', endDate: '2016-07-09T00:00:00.000-0400' },
{ value: 165, startDate: '2016-07-07T00:00:00.000-0400', endDate: '2016-07-08T00:00:00.000-0400' },
]
```
Query for respiratory rate samples. the options object is used to setup a query to retrieve relevant samples.
```javascript
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
```javascript
AppleHealthKit.getRespiratoryRateSamples(options, (err: Object, results: Array<Object>) => {
if (err) {
return;
}
console.log(results)
});
```
Query to get all activities of given type with extended information about it.
```javascript 1.7
let options = {
startDate: (new Date(2016,4,27)).toISOString(),
endDate: (new Date()).toISOString(),
type: 'Walking', // one of: ['Walking', 'StairClimbing', 'Running', 'Cycling', 'Workout']
};
```
The callback function will be called with a `samples` array containing objects with *value*, *startDate*, and *endDate* fields
```javascript 1.7
AppleHealthKit.getSamples(options, (err: Object, results: Array<Object>) => {
if (err) {
return;
}
console.log(results)
});
```
Resulting object has different fields for different types.
In case of workout:
```
{
activityId: Number, // [NSNumber numberWithInt:[sample workoutActivityType]]
activityName: Number, // [RCTAppleHealthKit stringForHKWorkoutActivityType:[sample workoutActivityType]]
calories: Number, // [[sample totalEnergyBurned] doubleValueForUnit:[HKUnit kilocalorieUnit]]
tracked: Boolean, // [[sample metadata][HKMetadataKeyWasUserEntered] intValue] !== 1
sourceName: String, // [[[sample sourceRevision] source] name]
sourceId: String, // [[[sample sourceRevision] source] bundleIdentifier]
device: String, // [[sample sourceRevision] productType] or 'iPhone'
distance: Number, // [[sample totalDistance] doubleValueForUnit:[HKUnit mileUnit]]
start: String, // [RCTAppleHealthKit buildISO8601StringFromDate:sample.startDate];
end: String, // [RCTAppleHealthKit buildISO8601StringFromDate:sample.endDate];
}
```
for other types:
```
{
tracked: Boolean, // [[sample metadata][HKMetadataKeyWasUserEntered] intValue] !== 1
sourceName: String, // [[[sample sourceRevision] source] name]
sourceId: String, // [[[sample sourceRevision] source] bundleIdentifier]
device: String, // [[sample sourceRevision] productType] or 'iPhone'
start: String, // [RCTAppleHealthKit buildISO8601StringFromDate:sample.startDate];
end: String, // [RCTAppleHealthKit buildISO8601StringFromDate:sample.endDate];
//based on required type, one of the following will be present.
distance: Number, // [[sample totalDistance] doubleValueForUnit:[HKUnit mileUnit]]
calories: Number, // [[sample totalEnergyBurned] doubleValueForUnit:[HKUnit kilocalorieUnit]]
}
```
Query for sleep samples.
Each sleep sample represents a period of time with a startDate and an endDate.
the sample's value will be either `INBED` or `ASLEEP`. these values should overlap,
meaning that two (or more) samples represent a single nights sleep activity. see
[Healthkit SleepAnalysis] reference documentation
The options object is used to setup a query to retrieve relevant samples.
The options must contain `startDate` and may also optionally include `endDate`
and `limit` options
```javascript
let options = {
startDate: (new Date(2016,10,1)).toISOString(), // required
endDate: (new Date()).toISOString(), // optional; default now
limit:10, // optional; default no limit
};
```
The callback function will be called with a `samples` array containing objects
with *value*, *startDate*, and *endDate* fields
```javascript
AppleHealthKit.getSleepSamples(options, (err: Object, results: Array<Object>) => {
if (err) {
return;
}
console.log(results).
});
```
\ No newline at end of file
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.
```javascript
let d = new Date(2016,1,1);
let options = {
date: d.toISOString()
};
```
```javascript
AppleHealthKit.getStepCount(options: Object, (err: Object, results: Object) => {
if (err) {
return;
}
console.log(results)
});
```
```javascript
{
value: 213,
}
```
\ No newline at end of file
Query for weight samples. the options object is used to setup a query to retrieve relevant samples.
```javascript
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
};
```
```javascript
AppleHealthKit.getWeightSamples(options, (err: Object, results: Array<Object>) => {
if (err) {
return;
}
console.log(results)
});
```
```javascript
[
{ value: 160, startDate: '2016-07-09T00:00:00.000-0400', endDate: '2016-07-10T00:00:00.000-0400' },
{ value: 161, startDate: '2016-07-08T00:00:00.000-0400', endDate: '2016-07-09T00:00:00.000-0400' },
{ value: 165, startDate: '2016-07-07T00:00:00.000-0400', endDate: '2016-07-08T00:00:00.000-0400' },
]
```
\ No newline at end of file
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
```javascript
let options = {
permissions: {
read: ["Height", "Weight", "StepCount", "DateOfBirth", "BodyMassIndex"],
write: ["Weight", "StepCount", "BodyMassIndex"]
}
};
```
```javascript
AppleHealthKit.initHealthKit(options: Object, (err: string, results: Object) => {
if (err) {
console.log("error initializing Healthkit: ", err);
return;
}
// Healthkit is initialized...
// now safe to read and write Healthkit data...
});
```
\ No newline at end of file
Setup an HKObserverQuery for step count (HKQuantityTypeIdentifierStepCount) that will
trigger an event listenable on react-native `NativeAppEventEmitter` when the
Healthkit step count has changed.
The `initStepCountObserver` method must be called before adding a listener to
NativeAppEventEmitter. After the step count observer has been initialized you can
listen to the NativeAppEventEmitter `change:steps` event and re-fetch relevent
step count data in the event handler.
The `initStepCountObserver` method should be called after Healthkit has been
successfully initialized (AppleHealthKit.initHealthKit has been called without
error).
```javascript
// import NativeAppEventEmitter from react-native
import {
Navigator,
View,
NativeAppEventEmitter,
} from 'react-native';
```
```javascript
AppleHealthKit.initHealthKit(HKOPTIONS, (err, res) => {
if (this._handleHKError(err, 'initHealthKit')) {
return;
}
// initialize the step count observer
AppleHealthKit.initStepCountObserver({}, () => {});
// add event listener for 'change:steps' and handle the
// event in the event handler function.
//
// when adding a listener, a 'subscription' object is
// returned that must be used to remove the listener
// when the component unmounts. The subscription object
// must be accessible to any function/method/instance
// that will be unsubscribing from the event.
this.sub = NativeAppEventEmitter.addListener(
'change:steps',
(evt) => {
// a 'change:steps' event has been received. step
// count data should be re-fetched from Healthkit.
this._fetchStepCountData();
}
);
// other tasks to perform after Healthkit has been
// initialized (fetch relevant Healthkit data).
this._fetchStepCountData();
this._fetchOtherRelevantHealthkitData();
// ...
});
...
// when the component where the listener was added unmounts
// (or whenever the listener should be removed), call the
// 'remove' method of the subscription object.
componentWillUnmount() {
this.sub.remove();
}
```
Check for Healthkit availability
```javascript
import AppleHealthKit from 'rn-apple-healthkit';
AppleHealthKit.isAvailable((err: Object, available: boolean) => {
if (err) {
console.log("error initializing Healthkit: ", err);
return;
}
// Healthkit is available
});
```
\ No newline at end of file
save a numeric BMI value to Healthkit
`saveBmi` accepts an options object containing a numeric BMI value:
```javascript
let options = {
value: 27.2
}
```
```javascript
AppleHealthKit.saveBmi(options: Object, (err: Object, results: Object) => {
if (err) {
return;
}
// BMI successfully saved
});
```
\ No newline at end of file
save a percentage body fat value to Healthkit
`saveBodyFatPercentage` accepts an options object containing a percent value:
```javascript
let options = {
value: 16.7 // 16.7%
}
```
```javascript
AppleHealthKit.saveBodyFatPercentage(options: Object, (err: Object, results: Object) => {
if (err) {
return;
}
// body fat percentage successfully saved
});
```
save a numeric height value to Healthkit
`saveHeight` accepts an options object containing a numeric height value:
```javascript
let options = {
value: 200 // Inches
}
```
```javascript
AppleHealthKit.saveHeight(options: Object, (err: Object, results: Object) => {
if (err) {
return;
}
// height successfully saved
});
```
\ No newline at end of file
save a numeric lean body mass value to Healthkit
`saveLeanBodyMass` accepts an options object containing a numeric weight value:
```javascript
let options = {
value: 155.6 // lbs
}
```
```javascript
AppleHealthKit.saveLeanBodyMass(options: Object, (err: Object, results: Object) => {
if (err) {
console.log("error saving lean body mass to Healthkit: ", err);
return;
}
// Done
});
```
Each mindfulness sample represents a period of time with a startDate and an endDate.
the options must contain `startDate` and `endDate`
```javascript
let options = {
startDate: (new Date(2016,10,1)).toISOString(), // required
endDate: (new Date()).toISOString(), // optional; default now
};
```
```
AppleHealthKit.saveMindfulSession(options, (err, res) => {
if (err) return {
return
}
console.log('Mindful session saved')
});
```
\ No newline at end of file
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`*.
```javascript
// startDate and endDate are 30 minutes apart.
// this means the step count value occurred 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()
};
```
```javascript
AppleHealthKit.saveSteps(options, (err, res) => {
if (this._handleHKError(err, 'saveSteps')) {
return;
}
// step count sample successfully saved
});
```
\ No newline at end of file
save a numeric weight value to Healthkit
`saveWeight` accepts an options object containing a numeric weight value:
```javascript
let options = {
value: 200
}
```
```javascript
AppleHealthKit.saveWeight(options: Object, (err: Object, results: Object) => {
if (err) {
console.log("error saving weight to Healthkit: ", err);
return;
}
// Done
});
```
\ No newline at end of file
Will listen for any updates in a given type data in healthKit and call app.
type - one of the `['Walking', 'StairClimbing', 'Running', 'Cycling', 'Workout']`
```javascript 1.8
import { NativeAppEventEmitter } from 'react-native';
//...//
AppleHealthKit.setObserver({ type: 'Walking' });
NativeAppEventEmitter.addListener(
'observer',
callback
);
```
So, callback would be call when new data of given type appears. When it happens, in order to get new info
need to call getSamples() function with proper arguments.
{ {
"name": "rn-apple-healthkit", "name": "rn-apple-healthkit",
"version": "0.6.0", "version": "0.6.5",
"description": "A React Native package for interacting with Apple HealthKit", "description": "A React Native package for interacting with Apple HealthKit",
"main": "index.js", "main": "index.js",
"repository": { "repository": {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment