RCTAppleHealthKit+Queries.m 9.15 KB
Newer Older
1 2 3 4 5 6 7 8 9
//
//  RCTAppleHealthKit+Queries.m
//  RCTAppleHealthKit
//
//  Created by Greg Wilson on 2016-06-26.
//  Copyright © 2016 Greg Wilson. All rights reserved.
//

#import "RCTAppleHealthKit+Queries.h"
10
#import "RCTAppleHealthKit+Utils.h"
11 12 13 14

@implementation RCTAppleHealthKit (Queries)


15
- (void)fetchMostRecentQuantitySampleOfType:(HKQuantityType *)quantityType predicate:(NSPredicate *)predicate completion:(void (^)(HKQuantity *, NSDate *, NSDate *, NSError *))completion { NSSortDescriptor *timeSortDescriptor = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierEndDate ascending:NO];
16

17
    HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:quantityType
18 19 20 21 22
                                                  predicate:predicate
                                                  limit:1
                                                  sortDescriptors:@[timeSortDescriptor]
                                                  resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {
                                                      if (!results) {
23
                                                          if (completion) {
24
                                                              completion(nil, nil, nil, error);
25
                                                          }
26 27 28 29 30 31 32
                                                          return;
                                                      }

                                                      if (completion) {
                                                          // If quantity isn't in the database, return nil in the completion block.
                                                          HKQuantitySample *quantitySample = results.firstObject;
                                                          HKQuantity *quantity = quantitySample.quantity;
33 34 35
                                                          NSDate *startDate = quantitySample.startDate;
                                                          NSDate *endDate = quantitySample.endDate;
                                                          completion(quantity, startDate, endDate, error);
36 37
                                                      }
                                                  }];
38

39 40 41 42 43 44
    [self.healthStore executeQuery:query];
}



- (void)fetchSumOfSamplesTodayForType:(HKQuantityType *)quantityType unit:(HKUnit *)unit completion:(void (^)(double, NSError *))completionHandler {
45
    NSPredicate *predicate = [RCTAppleHealthKit predicateForSamplesToday];
46
    
47 48 49 50
    HKStatisticsQuery *query = [[HKStatisticsQuery alloc] initWithQuantityType:quantityType
                                                          quantitySamplePredicate:predicate
                                                          options:HKStatisticsOptionCumulativeSum
                                                          completionHandler:^(HKStatisticsQuery *query, HKStatistics *result, NSError *error) {
51 52 53 54 55 56 57 58 59 60 61
        HKQuantity *sum = [result sumQuantity];
        
        if (completionHandler) {
            double value = [sum doubleValueForUnit:unit];
            completionHandler(value, error);
        }
    }];
    
    [self.healthStore executeQuery:query];
}

62 63 64 65 66 67


- (void)fetchSumOfSamplesOnDayForType:(HKQuantityType *)quantityType unit:(HKUnit *)unit day:(NSDate *)day completion:(void (^)(double, NSError *))completionHandler {
    NSPredicate *predicate = [RCTAppleHealthKit predicateForSamplesOnDay:day];

    HKStatisticsQuery *query = [[HKStatisticsQuery alloc] initWithQuantityType:quantityType
68 69 70 71 72
                                                          quantitySamplePredicate:predicate
                                                          options:HKStatisticsOptionCumulativeSum
                                                          completionHandler:^(HKStatisticsQuery *query, HKStatistics *result, NSError *error) {
                                                              HKQuantity *sum = [result sumQuantity];
                                                              if (completionHandler) {
73 74
                                                                     double value = [sum doubleValueForUnit:unit];
                                                                     completionHandler(value, error);
75 76
                                                              }
                                                          }];
77 78 79 80 81 82

    [self.healthStore executeQuery:query];
}



83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
//- (void)fetchSumOfSamplesBetweenDatesForType:(HKQuantityType *)quantityType unit:(HKUnit *)unit startDate:(NSDate *)startDate endDate:(NSDate *)endDate completion:(void (^)(NSArray *, NSError *))completionHandler {
//    NSPredicate *predicate = [RCTAppleHealthKit predicateForSamplesBetweenDates:startDate endDate:endDate];
//
//    HKStatisticsQuery *query = [[HKStatisticsQuery alloc] initWithQuantityType:quantityType
//                                                       quantitySamplePredicate:predicate
//                                                                       options:HKStatisticsOptionCumulativeSum
//                                                             completionHandler:^(HKStatisticsQuery *query, HKStatistics *result, NSError *error) {
//                                                                 HKQuantity *sum = [result sumQuantity];
//                                                                 if (completionHandler) {
//                                                                     double value = [sum doubleValueForUnit:unit];
//                                                                     completionHandler(value, error);
//                                                                 }
//                                                             }];
//
//    [self.healthStore executeQuery:query];
//}





- (void)fetchCumulativeSumStatisticsCollection:(HKQuantityType *)quantityType
                                          unit:(HKUnit *)unit
                                     startDate:(NSDate *)startDate
                                       endDate:(NSDate *)endDate
                                    completion:(void (^)(NSArray *, NSError *))completionHandler {

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *interval = [[NSDateComponents alloc] init];
    interval.day = 1;

    NSDateComponents *anchorComponents = [calendar components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear
                                                     fromDate:[NSDate date]];
    anchorComponents.hour = 0;
    NSDate *anchorDate = [calendar dateFromComponents:anchorComponents];
//    HKQuantityType *quantityType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];

// Create the query
    HKStatisticsCollectionQuery *query = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:quantityType
                                                                           quantitySamplePredicate:nil
                                                                                           options:HKStatisticsOptionCumulativeSum
                                                                                        anchorDate:anchorDate
                                                                                intervalComponents:interval];

// Set the results handler
    query.initialResultsHandler = ^(HKStatisticsCollectionQuery *query, HKStatisticsCollection *results, NSError *error) {
        if (error) {
            // Perform proper error handling here
            NSLog(@"*** An error occurred while calculating the statistics: %@ ***",error.localizedDescription);
        }

//        NSDate *endDate = [NSDate date];
//        NSDate *startDate = [calendar dateByAddingUnit:NSCalendarUnitDay
//                                                 value:-7
//                                                toDate:endDate
//                                               options:0];

        // Plot the daily step counts over the past 7 days

        NSMutableArray *data = [NSMutableArray arrayWithCapacity:1];

        [results enumerateStatisticsFromDate:startDate
                                      toDate:endDate
                                   withBlock:^(HKStatistics *result, BOOL *stop) {

                                       HKQuantity *quantity = result.sumQuantity;
                                       if (quantity) {
                                           NSDate *date = result.startDate;
                                           double value = [quantity doubleValueForUnit:[HKUnit countUnit]];
                                           NSLog(@"%@: %f", date, value);

                                           NSString *dateString = [RCTAppleHealthKit buildISO8601StringFromDate:date];

                                           NSArray *elem = @[dateString, @(value)];

                                           [data addObject:elem];
                                       }

                                   }];

//        NSArray *arr = @[@"Mercedes-Benz", @"BMW", @"Porsche", @"Opel", @"Volkswagen", @"Audi"];
        NSError *err;
        completionHandler(data, err);

    };

    [self.healthStore executeQuery:query];
}







178
@end