Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added implementation to fetch and delete food records in HealthKit #259

Open
wants to merge 1 commit into
base: development
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions RCTAppleHealthKit.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
64E0E73F1D37947B00EAB905 /* RCTAppleHealthKit+Methods_Results.m in Sources */ = {isa = PBXBuildFile; fileRef = 64E0E73E1D37947B00EAB905 /* RCTAppleHealthKit+Methods_Results.m */; };
8C640F40269DF69C004CAFED /* RCTAppleHealthKit+Methods_Hearing.m in Sources */ = {isa = PBXBuildFile; fileRef = 8C640F3F269DF69C004CAFED /* RCTAppleHealthKit+Methods_Hearing.m */; };
8C79D960268E081A00DBDC40 /* RCTAppleHealthKit+Methods_ClinicalRecords.m in Sources */ = {isa = PBXBuildFile; fileRef = 8C79D95F268E081A00DBDC40 /* RCTAppleHealthKit+Methods_ClinicalRecords.m */; };
A87E7EB32918ED3C00A63954 /* RCTAppleHealthKit+Methods_Dietary.m in Sources */ = {isa = PBXBuildFile; fileRef = A87E7EB22918ED3C00A63954 /* RCTAppleHealthKit+Methods_Dietary.m */; };
/* End PBXBuildFile section */

/* Begin PBXCopyFilesBuildPhase section */
Expand Down Expand Up @@ -75,6 +76,8 @@
8C640F3F269DF69C004CAFED /* RCTAppleHealthKit+Methods_Hearing.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = "RCTAppleHealthKit+Methods_Hearing.m"; sourceTree = "<group>"; };
8C79D95E268E07DB00DBDC40 /* RCTAppleHealthKit+Methods_ClinicalRecords.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "RCTAppleHealthKit+Methods_ClinicalRecords.h"; sourceTree = "<group>"; };
8C79D95F268E081A00DBDC40 /* RCTAppleHealthKit+Methods_ClinicalRecords.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = "RCTAppleHealthKit+Methods_ClinicalRecords.m"; sourceTree = "<group>"; };
A87E7EB12918ED3C00A63954 /* RCTAppleHealthKit+Methods_Dietary.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "RCTAppleHealthKit+Methods_Dietary.h"; sourceTree = "<group>"; };
A87E7EB22918ED3C00A63954 /* RCTAppleHealthKit+Methods_Dietary.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "RCTAppleHealthKit+Methods_Dietary.m"; sourceTree = "<group>"; };
/* End PBXFileReference section */

/* Begin PBXFrameworksBuildPhase section */
Expand Down Expand Up @@ -107,6 +110,8 @@
3774C88F1D2092F20000B3F3 /* RCTAppleHealthKit */ = {
isa = PBXGroup;
children = (
A87E7EB12918ED3C00A63954 /* RCTAppleHealthKit+Methods_Dietary.h */,
A87E7EB22918ED3C00A63954 /* RCTAppleHealthKit+Methods_Dietary.m */,
4F8095C72523C39D00A84ADB /* RCTAppleHealthKit+Methods_LabTests.h */,
4F8095C82523C39D00A84ADB /* RCTAppleHealthKit+Methods_LabTests.m */,
58C81E6E1F84F6970005DD48 /* RCTAppleHealthKit+Methods_Activity.h */,
Expand Down Expand Up @@ -205,6 +210,7 @@
3774C89B1D2095450000B3F3 /* RCTAppleHealthKit+Queries.m in Sources */,
3774C8A11D20A6B90000B3F3 /* RCTAppleHealthKit+Utils.m in Sources */,
8C640F40269DF69C004CAFED /* RCTAppleHealthKit+Methods_Hearing.m in Sources */,
A87E7EB32918ED3C00A63954 /* RCTAppleHealthKit+Methods_Dietary.m in Sources */,
37837E7D1DCFE270000201A0 /* RCTAppleHealthKit+Methods_Sleep.m in Sources */,
3774C8D41D20C6390000B3F3 /* RCTAppleHealthKit+Methods_Body.m in Sources */,
61232F931E303758000A5026 /* RCTAppleHealthKit+Methods_Mindfulness.m in Sources */,
Expand Down
2 changes: 2 additions & 0 deletions RCTAppleHealthKit/RCTAppleHealthKit+Methods_Dietary.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
@interface RCTAppleHealthKit (Methods_Dietary)

- (void)saveFood:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;
- (void)deleteFood:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;
- (void)getFood:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;

- (void)saveWater:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;
- (void)getWater:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback;
Expand Down
57 changes: 57 additions & 0 deletions RCTAppleHealthKit/RCTAppleHealthKit+Methods_Dietary.m
Original file line number Diff line number Diff line change
Expand Up @@ -477,6 +477,63 @@ - (void)saveFood:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback
}];
}

- (void)getFood:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback
{

NSDate *startDate = [RCTAppleHealthKit dateFromOptions:input key:@"startDate" withDefault:[NSDate date]];
NSDate *endDate = [RCTAppleHealthKit dateFromOptions:input key:@"endDate" withDefault:[NSDate date]];


if(startDate == nil) {
callback(@[RCTMakeError(@"could not parse start date from options.startDate", nil, nil)]);
return;
}

HKCorrelationType *dietaryFoodType = [HKCorrelationType correlationTypeForIdentifier:HKCorrelationTypeIdentifierFood];
NSPredicate * predicate = [RCTAppleHealthKit predicateForSamplesBetweenDates:startDate endDate:endDate];


[self fetchFoodSamples: dietaryFoodType
predicate:predicate
completion:^(NSArray *results, NSError *error) {
if(results){
callback(@[[NSNull null], results]);
return;
} else {
callback(@[RCTJSErrorFromNSError(error)]);
return;
}
}];
}

- (void)deleteFood:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback
{

NSDate *startDate = [RCTAppleHealthKit dateFromOptions:input key:@"startDate" withDefault:[NSDate date]];
NSDate *endDate = [RCTAppleHealthKit dateFromOptions:input key:@"endDate" withDefault:[NSDate date]];
NSString *objectId = [RCTAppleHealthKit stringFromOptions:input key:@"objectId" withDefault:nil];


if(startDate == nil) {
callback(@[RCTMakeError(@"could not parse start date from options.startDate", nil, nil)]);
return;
}
if(objectId == nil) {
callback(@[RCTMakeError(@"could not parse object id from options.objectId", nil, nil)]);
return;
}

NSPredicate * predicate = [RCTAppleHealthKit predicateForSamplesBetweenDates:startDate endDate:endDate];


[self deleteHealthKitObject:objectId type:[HKCorrelationType correlationTypeForIdentifier:HKCorrelationTypeIdentifierFood]
predicate:predicate
completion:^(BOOL success, NSError *error) {
callback(@[error == nil ? [NSNull null]: RCTJSErrorFromNSError(error), success ? @true : @false]);
return;
}];
}

- (void)saveWater:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback
{
NSDate *timeWaterWasConsumed = [RCTAppleHealthKit dateFromOptions:input key:@"date" withDefault:[NSDate date]];
Expand Down
10 changes: 10 additions & 0 deletions RCTAppleHealthKit/RCTAppleHealthKit+Queries.h
Original file line number Diff line number Diff line change
Expand Up @@ -118,4 +118,14 @@
endDate:(NSDate *)endDate
completion:(void (^)(NSArray *, NSError *))completionHandler;


- (void)fetchFoodSamples:(HKCorrelationType *)correlationType
predicate:(NSPredicate *)predicate
completion:(void (^)(NSArray *, NSError *))completion;

- (void)deleteHealthKitObject:(NSString *)objectId
type: (HKSampleType *)type
predicate:(NSPredicate *)predicate
completion:(void (^)(BOOL success, NSError *))completionHandler;

@end
109 changes: 109 additions & 0 deletions RCTAppleHealthKit/RCTAppleHealthKit+Queries.m
Original file line number Diff line number Diff line change
Expand Up @@ -1183,4 +1183,113 @@ - (void)fetchActivitySummary:(NSDate *)startDate

}

- (void)deleteHealthKitObject:(NSString *)objectId
type:(HKSampleType *)type
predicate:(NSPredicate *)predicate
completion:(void (^)(BOOL success, NSError *))completion {

// declare the block
void (^handlerBlock)(HKSampleQuery *query, NSArray *results, NSError *error);
void (^deleteBlock)(BOOL success, NSError *error);

// create and assign the block
deleteBlock = ^(BOOL success, NSError *error) {
if (completion) {
completion(success, error);
}
};
handlerBlock = ^(HKSampleQuery *query, NSArray *results, NSError *error) {
if (!results) {
if (completion) {
completion(false, nil);
}
return;
}
HKSample* found = [[results filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(HKSample* object, NSDictionary *bindings) {
return [[[object UUID] UUIDString] isEqualToString:objectId];
}]] firstObject];
if(!found) {
if (completion) {
completion(false, nil);
}
return;
}
[self.healthStore deleteObject:found withCompletion:deleteBlock];
};
HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType: type
predicate:predicate
limit:HKObjectQueryNoLimit
sortDescriptors:@[]
resultsHandler:handlerBlock];

[self.healthStore executeQuery:query];
}

- (void)fetchFoodSamples:(HKCorrelationType *)correlationType
predicate:(NSPredicate *)predicate
completion:(void (^)(NSArray *, NSError *))completion {

// declare the block
void (^handlerBlock)(HKCorrelationQuery *query, NSArray *results, NSError *error);
// create and assign the block
handlerBlock = ^(HKCorrelationQuery *query, NSArray *results, NSError *error) {
if (!results) {
if (completion) {
completion(nil, error);
}
return;
}

if (completion) {
NSMutableArray *data = [NSMutableArray arrayWithCapacity:1];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

for (HKCorrelation *result in results) {

NSString *startDateString = [RCTAppleHealthKit buildISO8601StringFromDate:result.startDate];
NSString *endDateString = [RCTAppleHealthKit buildISO8601StringFromDate:result.endDate];

NSMutableDictionary *value = [[NSMutableDictionary alloc] init];
NSSet *objects = [result objects];
if (objects) {
for(HKQuantitySample* obj in objects) {
NSString* nutrient = [RCTAppleHealthKit getSimpleNameForHKIdentifierType: [[obj quantityType] identifier]];
double val = 0;
if([[obj quantityType] identifier] == HKQuantityTypeIdentifierDietaryEnergyConsumed){
val= [[obj quantity] doubleValueForUnit:[HKUnit kilocalorieUnit]];
}else{
val = [[obj quantity] doubleValueForUnit:[HKUnit gramUnit]];
}
[value setValue:[NSNumber numberWithDouble: val] forKey:nutrient];
}
}


NSMutableDictionary *elem = [NSMutableDictionary dictionaryWithDictionary:@{
@"nutrients" : value,
@"id" : [[result UUID] UUIDString],
@"sourceName" : [[[result sourceRevision] source] name],
@"sourceId" : [[[result sourceRevision] source] bundleIdentifier],
@"startDate" : startDateString,
@"endDate" : endDateString,
}];

NSDictionary *metadata = [result metadata];
if (metadata) {
[elem setValue:metadata forKey:kMetadataKey];
}

[data addObject:elem];
}

completion(data, error);
});
}
};

HKCorrelationQuery *query = [[HKCorrelationQuery alloc] initWithType:correlationType predicate:predicate samplePredicates:nil completion:handlerBlock];

[self.healthStore executeQuery:query];
}
@end
1 change: 1 addition & 0 deletions RCTAppleHealthKit/RCTAppleHealthKit+Utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -40,5 +40,6 @@ extern NSString * const kMetadataKey;

+ (NSMutableArray *)reverseNSMutableArray:(NSMutableArray *)array;
+ (NSString*) stringForHKWorkoutActivityType:(int) enumValue;
+ (NSString*) getSimpleNameForHKIdentifierType:(HKQuantityTypeIdentifier) type;

@end
116 changes: 116 additions & 0 deletions RCTAppleHealthKit/RCTAppleHealthKit+Utils.m
Original file line number Diff line number Diff line change
Expand Up @@ -577,4 +577,120 @@ + (NSString*)stringForHKWorkoutActivityType:(int) enumValue{
}
}


+(NSString*) getSimpleNameForHKIdentifierType:(HKQuantityTypeIdentifier)type {
if(type == HKQuantityTypeIdentifierDietaryBiotin) {
return @"biotin";
}
if(type == HKQuantityTypeIdentifierDietaryCaffeine) {
return @"caffeine";
}
if(type == HKQuantityTypeIdentifierDietaryCalcium) {
return @"calcium";
}
if(type == HKQuantityTypeIdentifierDietaryCarbohydrates) {
return @"carbohydrates";
}
if(type == HKQuantityTypeIdentifierDietaryChloride) {
return @"cloride";
}
if(type == HKQuantityTypeIdentifierDietaryCholesterol) {
return @"cholesterol";
}
if(type == HKQuantityTypeIdentifierDietaryCopper) {
return @"copper";
}
if(type == HKQuantityTypeIdentifierDietaryEnergyConsumed) {
return @"energy";
}
if(type == HKQuantityTypeIdentifierDietaryFatMonounsaturated) {
return @"fatMonounsaturated";
}
if(type == HKQuantityTypeIdentifierDietaryFatPolyunsaturated) {
return @"fatPolyunsaturated";
}
if(type == HKQuantityTypeIdentifierDietaryFatSaturated) {
return @"fatSaturated";
}
if(type == HKQuantityTypeIdentifierDietaryFatTotal) {
return @"fatTotal";
}
if(type == HKQuantityTypeIdentifierDietaryFiber) {
return @"fiber";
}
if(type == HKQuantityTypeIdentifierDietaryFolate) {
return @"folate";
}
if(type == HKQuantityTypeIdentifierDietaryIodine) {
return @"iodine";
}
if(type == HKQuantityTypeIdentifierDietaryIron) {
return @"iron";
}
if(type == HKQuantityTypeIdentifierDietaryMagnesium) {
return @"magnesium";
}
if(type == HKQuantityTypeIdentifierDietaryManganese) {
return @"manganese";
}
if(type == HKQuantityTypeIdentifierDietaryMolybdenum) {
return @"molybdenum";
}
if(type == HKQuantityTypeIdentifierDietaryNiacin) {
return @"niacin";
}
if(type == HKQuantityTypeIdentifierDietaryPantothenicAcid) {
return @"pantothenicAcid";
}
if(type == HKQuantityTypeIdentifierDietaryPhosphorus) {
return @"phosphorus";
}
if(type == HKQuantityTypeIdentifierDietaryPotassium) {
return @"potassium";
}
if(type == HKQuantityTypeIdentifierDietaryProtein) {
return @"protein";
}
if(type == HKQuantityTypeIdentifierDietaryRiboflavin) {
return @"riboflavin";
}
if(type == HKQuantityTypeIdentifierDietarySelenium) {
return @"selenium";
}
if(type == HKQuantityTypeIdentifierDietarySodium) {
return @"sodium";
}
if(type == HKQuantityTypeIdentifierDietarySugar) {
return @"sugar";
}
if(type == HKQuantityTypeIdentifierDietaryThiamin) {
return @"thiamin";
}
if(type == HKQuantityTypeIdentifierDietaryVitaminA) {
return @"vitaminA";
}
if(type == HKQuantityTypeIdentifierDietaryVitaminB12) {
return @"vitaminB12";
}
if(type == HKQuantityTypeIdentifierDietaryVitaminB6) {
return @"vitaminB6";
}
if(type == HKQuantityTypeIdentifierDietaryVitaminC) {
return @"vitaminC";
}
if(type == HKQuantityTypeIdentifierDietaryVitaminD) {
return @"vitaminD";
}
if(type == HKQuantityTypeIdentifierDietaryVitaminE) {
return @"vitaminE";
}
if(type == HKQuantityTypeIdentifierDietaryVitaminK) {
return @"vitaminK";
}
if(type == HKQuantityTypeIdentifierDietaryZinc) {
return @"zinc";
}
return @"Unkown";
}

@end
12 changes: 12 additions & 0 deletions RCTAppleHealthKit/RCTAppleHealthKit.m
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,18 @@ + (BOOL)requiresMainQueueSetup
[self saveFood:input callback:callback];
}

RCT_EXPORT_METHOD(getFood:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback)
{
[self _initializeHealthStore];
[self getFood:input callback:callback];
}

RCT_EXPORT_METHOD(deleteFood:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback)
{
[self _initializeHealthStore];
[self deleteFood:input callback:callback];
}

RCT_EXPORT_METHOD(saveWater:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback)
{
[self _initializeHealthStore];
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,8 @@ they are splitted in the following categories
- [getProteinSamples](/docs/getProteinSamples.md)
- [getTotalFatSamples](/docs/getTotalFatSamples.md)
- [saveFood](/docs/saveFood.md)
- [getFood](/docs/getFood.md)
- [deleteFood](/docs/deleteFood.md)
- [saveWater](/docs/saveWater.md)
- [getWater](/docs/getWater.md)

Expand Down
Loading