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

#import "RCTAppleHealthKit+Queries.h"
10
#import "RCTAppleHealthKit+Utils.h"
11

Evgenii Evstropov's avatar
Evgenii Evstropov committed
12 13 14
#import <React/RCTBridgeModule.h>
#import <React/RCTEventDispatcher.h>

15 16
@implementation RCTAppleHealthKit (Queries)

17 18 19
- (void)fetchMostRecentQuantitySampleOfType:(HKQuantityType *)quantityType
                                  predicate:(NSPredicate *)predicate
                                 completion:(void (^)(HKQuantity *, NSDate *, NSDate *, NSError *))completion {
20

21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
    NSSortDescriptor *timeSortDescriptor = [[NSSortDescriptor alloc]
            initWithKey:HKSampleSortIdentifierEndDate
              ascending:NO
    ];

    HKSampleQuery *query = [[HKSampleQuery alloc]
            initWithSampleType:quantityType
                     predicate:predicate
                         limit:1
               sortDescriptors:@[timeSortDescriptor]
                resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {

                      if (!results) {
                          if (completion) {
                              completion(nil, nil, nil, error);
                          }
                          return;
                      }

                      if (completion) {
                          // If quantity isn't in the database, return nil in the completion block.
                          HKQuantitySample *quantitySample = results.firstObject;
                          HKQuantity *quantity = quantitySample.quantity;
                          NSDate *startDate = quantitySample.startDate;
                          NSDate *endDate = quantitySample.endDate;
                          completion(quantity, startDate, endDate, error);
                      }
                }
    ];
50 51 52
    [self.healthStore executeQuery:query];
}

53 54 55 56 57 58
- (void)fetchQuantitySamplesOfType:(HKQuantityType *)quantityType
                              unit:(HKUnit *)unit
                         predicate:(NSPredicate *)predicate
                         ascending:(BOOL)asc
                             limit:(NSUInteger)lim
                        completion:(void (^)(NSArray *, NSError *))completion {
59
    
60 61
    NSSortDescriptor *timeSortDescriptor = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierEndDate
                                                                       ascending:asc];
62
    
63 64 65 66 67 68 69 70 71 72
    // declare the block
    void (^handlerBlock)(HKSampleQuery *query, NSArray *results, NSError *error);
    // create and assign the block
    handlerBlock = ^(HKSampleQuery *query, NSArray *results, NSError *error) {
        if (!results) {
            if (completion) {
                completion(nil, error);
            }
            return;
        }
73
        
74 75
        if (completion) {
            NSMutableArray *data = [NSMutableArray arrayWithCapacity:1];
76
            
77
            dispatch_async(dispatch_get_main_queue(), ^{
78
                
79 80 81
                for (HKQuantitySample *sample in results) {
                    HKQuantity *quantity = sample.quantity;
                    double value = [quantity doubleValueForUnit:unit];
82
                    
83 84
                    NSString *startDateString = [RCTAppleHealthKit buildISO8601StringFromDate:sample.startDate];
                    NSString *endDateString = [RCTAppleHealthKit buildISO8601StringFromDate:sample.endDate];
85
                    
86
                    NSDictionary *elem = @{
87 88 89 90 91
                                           @"value" : @(value),
                                           @"startDate" : startDateString,
                                           @"endDate" : endDateString,
                                           };
                    
92 93
                    [data addObject:elem];
                }
94
                
95 96 97 98
                completion(data, error);
            });
        }
    };
99
    
100 101 102 103 104
    HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:quantityType
                                                           predicate:predicate
                                                               limit:lim
                                                     sortDescriptors:@[timeSortDescriptor]
                                                      resultsHandler:handlerBlock];
105
    
106 107 108
    [self.healthStore executeQuery:query];
}

109 110 111


- (void)fetchSamplesOfType:(HKSampleType *)type
EEvgeniiF's avatar
EEvgeniiF committed
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
                              unit:(HKUnit *)unit
                         predicate:(NSPredicate *)predicate
                         ascending:(BOOL)asc
                             limit:(NSUInteger)lim
                        completion:(void (^)(NSArray *, NSError *))completion {
    NSSortDescriptor *timeSortDescriptor = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierEndDate
                                                                       ascending:asc];
    
    // declare the block
    void (^handlerBlock)(HKSampleQuery *query, NSArray *results, NSError *error);
    // create and assign the block
    handlerBlock = ^(HKSampleQuery *query, NSArray *results, NSError *error) {
        if (!results) {
            if (completion) {
                completion(nil, error);
            }
            return;
        }
        
        if (completion) {
            NSMutableArray *data = [NSMutableArray arrayWithCapacity:1];
            
            dispatch_async(dispatch_get_main_queue(), ^{
135 136
                if (type == [HKObjectType workoutType]) {
                    for (HKWorkout *sample in results) {
137 138 139
                        double energy =  [[sample totalEnergyBurned] doubleValueForUnit:[HKUnit kilocalorieUnit]];
                        double distance = [[sample totalDistance] doubleValueForUnit:[HKUnit mileUnit]];
                        NSString *type = [RCTAppleHealthKit stringForHKWorkoutActivityType:[sample workoutActivityType]];
140 141 142
                        
                        NSString *startDateString = [RCTAppleHealthKit buildISO8601StringFromDate:sample.startDate];
                        NSString *endDateString = [RCTAppleHealthKit buildISO8601StringFromDate:sample.endDate];
143
                        
144
                        bool isTracked = true;
145 146 147
                        if ([[sample metadata][HKMetadataKeyWasUserEntered] intValue] == 1) {
                            isTracked = false;
                        }
148 149
                        
                        NSDictionary *elem = @{
150
                                               @"activityName" : [NSNumber numberWithInt:[sample workoutActivityType]],
Evgenii Evstropov's avatar
Evgenii Evstropov committed
151 152
                                               @"calories" : @(energy),
                                               @"tracked" : @(isTracked),
153
                                               @"sourceName" : [[[sample sourceRevision] source] name],
Evgenii Evstropov's avatar
Evgenii Evstropov committed
154
                                               @"sourceId" : [[[sample sourceRevision] source] bundleIdentifier],
155
                                               @"device": [[sample sourceRevision] productType],
156
                                               @"distance" : @(distance),
Evgenii Evstropov's avatar
Evgenii Evstropov committed
157 158
                                               @"start" : startDateString,
                                               @"end" : endDateString
159 160 161 162 163 164 165 166 167
                                               };
                        
                        [data addObject:elem];
                    }
                } else {
                    for (HKQuantitySample *sample in results) {
                        HKQuantity *quantity = sample.quantity;
                        double value = [quantity doubleValueForUnit:unit];
                        
168 169 170 171 172
                        NSString * valueType = @"quantity";
                        if (unit == [HKUnit mileUnit]) {
                            valueType = @"distance";
                        }
                        
173 174 175
                        NSString *startDateString = [RCTAppleHealthKit buildISO8601StringFromDate:sample.startDate];
                        NSString *endDateString = [RCTAppleHealthKit buildISO8601StringFromDate:sample.endDate];
                        
176
                        bool isTracked = true;
177 178 179
                        if ([[sample metadata][HKMetadataKeyWasUserEntered] intValue] == 1) {
                            isTracked = false;
                        }
180
                        
181
                        NSDictionary *elem = @{
182
                                               valueType : @(value),
Evgenii Evstropov's avatar
Evgenii Evstropov committed
183
                                               @"tracked" : @(isTracked),
184
                                               @"sourceName" : [[[sample sourceRevision] source] name],
Evgenii Evstropov's avatar
Evgenii Evstropov committed
185
                                               @"sourceId" : [[[sample sourceRevision] source] bundleIdentifier],
186
                                               @"device": [[sample sourceRevision] productType],
Evgenii Evstropov's avatar
Evgenii Evstropov committed
187 188
                                               @"start" : startDateString,
                                               @"end" : endDateString
189 190 191 192
                                               };
                        
                        [data addObject:elem];
                    }
EEvgeniiF's avatar
EEvgeniiF committed
193 194 195 196 197 198 199
                }
                
                completion(data, error);
            });
        }
    };
    
200
    HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:type
EEvgeniiF's avatar
EEvgeniiF committed
201 202 203 204 205 206 207
                                                           predicate:predicate
                                                               limit:lim
                                                     sortDescriptors:@[timeSortDescriptor]
                                                      resultsHandler:handlerBlock];
    
    [self.healthStore executeQuery:query];
}
208

Evgenii Evstropov's avatar
Evgenii Evstropov committed
209
- (void)setObserverForType:(HKSampleType *)type
210
                      unit:(HKUnit *)unit {
Evgenii Evstropov's avatar
Evgenii Evstropov committed
211
    NSLog(@"set observer");
212
    HKObserverQuery *query = [[HKObserverQuery alloc] initWithSampleType:type predicate:nil updateHandler:^(HKObserverQuery *query, HKObserverQueryCompletionHandler completionHandler, NSError * _Nullable error){
Evgenii Evstropov's avatar
Evgenii Evstropov committed
213
        UIApplication *app = [UIApplication sharedApplication];
214 215 216 217 218
        NSLog(@"observer fired");
        [self.bridge.eventDispatcher sendAppEventWithName:@"observer"             body:@""];
        completionHandler();
//        self.isSync = true;
//        __block UIBackgroundTaskIdentifier backgroundTaskIdentifier = [app beginBackgroundTaskWithExpirationHandler:^{
Evgenii Evstropov's avatar
Evgenii Evstropov committed
219
//
220 221 222
//            NSLog(@"observer fired from bg");
//            [self.bridge.eventDispatcher sendAppEventWithName:@"observer"
//                                                         body:@""];
Evgenii Evstropov's avatar
Evgenii Evstropov committed
223
//
224 225 226 227 228
//            [app endBackgroundTask:backgroundTaskIdentifier];
//            completionHandler();
//            self.isSync = false;
//        }];
    }];
Evgenii Evstropov's avatar
Evgenii Evstropov committed
229 230 231 232 233 234
    
    [self.healthStore executeQuery:query];
    [self.healthStore enableBackgroundDeliveryForType:type frequency:HKUpdateFrequencyImmediate withCompletion:^(BOOL success, NSError * _Nullable error) {
        NSLog(@"success %s print some error %@", success ? "true" : "false", [error localizedDescription]);
    }];
}
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262

- (void)fetchSleepCategorySamplesForPredicate:(NSPredicate *)predicate
                                   limit:(NSUInteger)lim
                                   completion:(void (^)(NSArray *, NSError *))completion {


    NSSortDescriptor *timeSortDescriptor = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierEndDate
                                                                       ascending:false];


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

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

            dispatch_async(dispatch_get_main_queue(), ^{

                for (HKCategorySample *sample in results) {

263
                    // HKCategoryType *catType = sample.categoryType;
264
                    NSInteger val = sample.value;
265 266 267 268 269 270 271

                    // HKQuantity *quantity = sample.quantity;
                    // double value = [quantity doubleValueForUnit:unit];

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

272 273 274 275 276 277 278 279 280 281 282 283 284 285
                    NSString *valueString;

                    switch (val) {
                      case HKCategoryValueSleepAnalysisInBed:
                        valueString = @"INBED";
                      break;
                      case HKCategoryValueSleepAnalysisAsleep:
                        valueString = @"ASLEEP";
                      break;
                     default:
                        valueString = @"UNKNOWN";
                     break;
                  }

286
                    NSDictionary *elem = @{
287
                            @"value" : valueString,
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
                            @"startDate" : startDateString,
                            @"endDate" : endDateString,
                    };

                    [data addObject:elem];
                }

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

    // HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:quantityType
    //                                                        predicate:predicate
    //                                                            limit:lim
    //                                                  sortDescriptors:@[timeSortDescriptor]
    //                                                   resultsHandler:handlerBlock];

    HKCategoryType *categoryType =
    [HKObjectType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis];

    // HKCategorySample *categorySample =
    // [HKCategorySample categorySampleWithType:categoryType
    //                                    value:value
    //                                startDate:startDate
    //                                  endDate:endDate];


   HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:categoryType
                                                          predicate:predicate
                                                              limit:lim
                                                    sortDescriptors:@[timeSortDescriptor]
                                                     resultsHandler:handlerBlock];


    [self.healthStore executeQuery:query];
}













338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
- (void)fetchCorrelationSamplesOfType:(HKQuantityType *)quantityType
                                 unit:(HKUnit *)unit
                            predicate:(NSPredicate *)predicate
                            ascending:(BOOL)asc
                                limit:(NSUInteger)lim
                           completion:(void (^)(NSArray *, NSError *))completion {

    NSSortDescriptor *timeSortDescriptor = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierEndDate
                                                                       ascending:asc];

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

359 360 361 362 363 364 365 366 367 368
        if (completion) {
            NSMutableArray *data = [NSMutableArray arrayWithCapacity:1];

            dispatch_async(dispatch_get_main_queue(), ^{

                for (HKCorrelation *sample in results) {
                    NSString *startDateString = [RCTAppleHealthKit buildISO8601StringFromDate:sample.startDate];
                    NSString *endDateString = [RCTAppleHealthKit buildISO8601StringFromDate:sample.endDate];

                    NSDictionary *elem = @{
Greg Wilson's avatar
Greg Wilson committed
369 370 371 372
                      @"correlation" : sample,
                      @"startDate" : startDateString,
                      @"endDate" : endDateString,
                    };
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
                    [data addObject:elem];
                }

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

    HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:quantityType
                                                           predicate:predicate
                                                               limit:lim
                                                     sortDescriptors:@[timeSortDescriptor]
                                                      resultsHandler:handlerBlock];

    [self.healthStore executeQuery:query];
}
389 390


391 392 393 394
- (void)fetchSumOfSamplesTodayForType:(HKQuantityType *)quantityType
                                 unit:(HKUnit *)unit
                           completion:(void (^)(double, NSError *))completionHandler {

395
    NSPredicate *predicate = [RCTAppleHealthKit predicateForSamplesToday];
396 397 398 399
    HKStatisticsQuery *query = [[HKStatisticsQuery alloc] initWithQuantityType:quantityType
                                                          quantitySamplePredicate:predicate
                                                          options:HKStatisticsOptionCumulativeSum
                                                          completionHandler:^(HKStatisticsQuery *query, HKStatistics *result, NSError *error) {
400 401 402 403 404 405
                                                                HKQuantity *sum = [result sumQuantity];
                                                                if (completionHandler) {
                                                                    double value = [sum doubleValueForUnit:unit];
                                                                    completionHandler(value, error);
                                                                }
                                                          }];
Greg Wilson's avatar
Greg Wilson committed
406

407 408 409
    [self.healthStore executeQuery:query];
}

410

411 412 413
- (void)fetchSumOfSamplesOnDayForType:(HKQuantityType *)quantityType
                                 unit:(HKUnit *)unit
                                  day:(NSDate *)day
414
                           completion:(void (^)(double, NSDate *, NSDate *, NSError *))completionHandler {
415

416
    NSPredicate *predicate = [RCTAppleHealthKit predicateForSamplesOnDay:day];
417
    HKStatisticsQuery *query = [[HKStatisticsQuery alloc] initWithQuantityType:quantityType
418 419 420 421
                                                          quantitySamplePredicate:predicate
                                                          options:HKStatisticsOptionCumulativeSum
                                                          completionHandler:^(HKStatisticsQuery *query, HKStatistics *result, NSError *error) {
                                                              HKQuantity *sum = [result sumQuantity];
422 423
                                                              NSDate *startDate = result.startDate;
                                                              NSDate *endDate = result.endDate;
424
                                                              if (completionHandler) {
425
                                                                     double value = [sum doubleValueForUnit:unit];
426
                                                                     completionHandler(value,startDate, endDate, error);
427 428
                                                              }
                                                          }];
429 430 431 432 433

    [self.healthStore executeQuery:query];
}


434 435 436 437
- (void)fetchCumulativeSumStatisticsCollection:(HKQuantityType *)quantityType
                                          unit:(HKUnit *)unit
                                     startDate:(NSDate *)startDate
                                       endDate:(NSDate *)endDate
438
                                    completion:(void (^)(NSArray *, NSError *))completionHandler {
439 440 441 442 443 444 445 446 447 448

    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];

449
    // Create the query
450 451 452 453 454 455
    HKStatisticsCollectionQuery *query = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:quantityType
                                                                           quantitySamplePredicate:nil
                                                                                           options:HKStatisticsOptionCumulativeSum
                                                                                        anchorDate:anchorDate
                                                                                intervalComponents:interval];

456
    // Set the results handler
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
    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);
        }

        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];
                                       }
                                   }];
        NSError *err;
        completionHandler(data, err);
    };

    [self.healthStore executeQuery:query];
}


487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
- (void)fetchCumulativeSumStatisticsCollection:(HKQuantityType *)quantityType
                                          unit:(HKUnit *)unit
                                     startDate:(NSDate *)startDate
                                       endDate:(NSDate *)endDate
                                     ascending:(BOOL)asc
                                         limit:(NSUInteger)lim
                                    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];

    // 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);
        }

        NSMutableArray *data = [NSMutableArray arrayWithCapacity:1];

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

                                       HKQuantity *quantity = result.sumQuantity;
                                       if (quantity) {
                                           NSDate *startDate = result.startDate;
                                           NSDate *endDate = result.endDate;
                                           double value = [quantity doubleValueForUnit:unit];

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

                                           NSDictionary *elem = @{
                                                   @"value" : @(value),
                                                   @"startDate" : startDateString,
                                                   @"endDate" : endDateString,
                                           };
                                           [data addObject:elem];
                                       }
                                   }];
        // is ascending by default
        if(asc == false) {
543
            [RCTAppleHealthKit reverseNSMutableArray:data];
544 545
        }

546
        if((lim > 0) && ([data count] > lim)) {
547 548 549 550 551 552 553 554 555 556 557 558
            NSArray* slicedArray = [data subarrayWithRange:NSMakeRange(0, lim)];
            NSError *err;
            completionHandler(slicedArray, err);
        } else {
            NSError *err;
            completionHandler(data, err);
        }
    };

    [self.healthStore executeQuery:query];
}

559
@end