RCTAppleHealthKit+Queries.m 54 KB
Newer Older
1 2 3 4 5
//
//  RCTAppleHealthKit+Queries.m
//  RCTAppleHealthKit
//
//  Created by Greg Wilson on 2016-06-26.
6 7
//  This source code is licensed under the MIT-style license found in the
//  LICENSE file in the root directory of this source tree.
8 9 10
//

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

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

@implementation RCTAppleHealthKit (Queries)

18 19 20
- (void)fetchMostRecentQuantitySampleOfType:(HKQuantityType *)quantityType
                                  predicate:(NSPredicate *)predicate
                                 completion:(void (^)(HKQuantity *, NSDate *, NSDate *, NSError *))completion {
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 50
    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);
                      }
                }
    ];
51 52 53
    [self.healthStore executeQuery:query];
}

54 55 56 57 58 59 60
- (void)fetchQuantitySamplesOfType:(HKQuantityType *)quantityType
                              unit:(HKUnit *)unit
                         predicate:(NSPredicate *)predicate
                         ascending:(BOOL)asc
                             limit:(NSUInteger)lim
                        completion:(void (^)(NSArray *, NSError *))completion {

61 62 63 64 65 66 67 68 69 70 71 72 73
    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;
        }
74

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

78
            dispatch_async(dispatch_get_main_queue(), ^{
79

80 81
                for (HKQuantitySample *sample in results) {
                    HKQuantity *quantity = sample.quantity;
王品堯's avatar
王品堯 committed
82
                    int value = round([quantity doubleValueForUnit:unit]);
83

王品堯's avatar
王品堯 committed
84 85
                    int startDateTimestamp = [RCTAppleHealthKit buildTimestampFromDate:sample.startDate];
                    int endDateTimestamp = [RCTAppleHealthKit buildTimestampFromDate:sample.endDate];
86 87 88 89 90 91 92 93 94 95 96
                    
                    NSString *deviceName = sample.device.name ? sample.device.name : @"";
                    NSString *deviceManufacturer = sample.device.manufacturer ? sample.device.manufacturer : @"";
                    NSString *deviceHardwareVer = sample.device.hardwareVersion ? sample.device.hardwareVersion : @"";
                    NSString *deviceSoftwareVer = sample.device.softwareVersion ? sample.device.softwareVersion : @"";
                    
                    NSString *sourceName = sample.sourceRevision.source.name;
                    NSString *sourceId = sample.sourceRevision.source.bundleIdentifier;
                    
                    NSString *uuid = sample.UUID.UUIDString;
                    
王品堯's avatar
王品堯 committed
97 98 99
                    NSString *metadata = [sample.metadata == nil ? @"" : sample.metadata.description stringByReplacingOccurrencesOfString:@" " withString:@""];
                    metadata = [metadata stringByReplacingOccurrencesOfString:@"\r" withString:@""];
                    metadata = [metadata stringByReplacingOccurrencesOfString:@"\n" withString:@""];
100
                    
101 102
                    NSDictionary *elem = @{
                            @"value" : @(value),
王品堯's avatar
王品堯 committed
103 104
                            @"startDate" : @(startDateTimestamp),
                            @"endDate" : @(endDateTimestamp),
105 106 107 108 109 110 111 112 113
                            @"deviceName" : deviceName,
                            @"deviceManufacturer" : deviceManufacturer,
                            @"deviceHardware" : deviceHardwareVer,
                            @"deviceSoftware" : deviceSoftwareVer,
                            @"sourceName" : sourceName,
                            @"sourceId" : sourceId,
                            @"unit" : unit.description,
                            @"uuid" : uuid,
                            @"metadata" : metadata
114
                    };
115

116 117
                    [data addObject:elem];
                }
118

119 120 121 122
                completion(data, error);
            });
        }
    };
123

124 125 126 127 128 129
    HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:quantityType
                                                           predicate:predicate
                                                               limit:lim
                                                     sortDescriptors:@[timeSortDescriptor]
                                                      resultsHandler:handlerBlock];

130 131 132
    [self.healthStore executeQuery:query];
}

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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
- (void)fetchQuantityDoubleSamplesOfType:(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;
        }
        
        if (completion) {
            NSMutableArray *data = [NSMutableArray arrayWithCapacity:1];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                for (HKQuantitySample *sample in results) {
                    HKQuantity *quantity = sample.quantity;
                    double value = [quantity doubleValueForUnit:unit];
                    
                    int startDateTimestamp = [RCTAppleHealthKit buildTimestampFromDate:sample.startDate];
                    int endDateTimestamp = [RCTAppleHealthKit buildTimestampFromDate:sample.endDate];
                    
                    NSString *deviceName = sample.device.name ? sample.device.name : @"";
                    NSString *deviceManufacturer = sample.device.manufacturer ? sample.device.manufacturer : @"";
                    NSString *deviceHardwareVer = sample.device.hardwareVersion ? sample.device.hardwareVersion : @"";
                    NSString *deviceSoftwareVer = sample.device.softwareVersion ? sample.device.softwareVersion : @"";
                    
                    NSString *sourceName = sample.sourceRevision.source.name;
                    NSString *sourceId = sample.sourceRevision.source.bundleIdentifier;
                    
                    NSString *uuid = sample.UUID.UUIDString;
                    
                    NSString *metadata = [sample.metadata == nil ? @"" : sample.metadata.description stringByReplacingOccurrencesOfString:@" " withString:@""];
                    metadata = [metadata stringByReplacingOccurrencesOfString:@"\r" withString:@""];
                    metadata = [metadata stringByReplacingOccurrencesOfString:@"\n" withString:@""];
                    
                    NSDictionary *elem = @{
                                           @"value" : @(value),
                                           @"startDate" : @(startDateTimestamp),
                                           @"endDate" : @(endDateTimestamp),
                                           @"deviceName" : deviceName,
                                           @"deviceManufacturer" : deviceManufacturer,
                                           @"deviceHardware" : deviceHardwareVer,
                                           @"deviceSoftware" : deviceSoftwareVer,
                                           @"sourceName" : sourceName,
                                           @"sourceId" : sourceId,
                                           @"unit" : unit.description,
                                           @"uuid" : uuid,
                                           @"metadata" : metadata
                                           };
                    
                    [data addObject:elem];
                }
                
                completion(data, error);
            });
        }
    };
    
    HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:quantityType
                                                           predicate:predicate
                                                               limit:lim
                                                     sortDescriptors:@[timeSortDescriptor]
                                                      resultsHandler:handlerBlock];
    
    [self.healthStore executeQuery:query];
}
211

212
- (void)fetchSamplesOfType:(HKSampleType *)type
EEvgeniiF's avatar
EEvgeniiF committed
213 214 215 216 217 218 219
                              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];
220

EEvgeniiF's avatar
EEvgeniiF committed
221 222 223 224 225 226 227 228 229 230
    // 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;
        }
231

EEvgeniiF's avatar
EEvgeniiF committed
232 233
        if (completion) {
            NSMutableArray *data = [NSMutableArray arrayWithCapacity:1];
234

EEvgeniiF's avatar
EEvgeniiF committed
235
            dispatch_async(dispatch_get_main_queue(), ^{
236 237
                if (type == [HKObjectType workoutType]) {
                    for (HKWorkout *sample in results) {
238 239 240
                        double energy =  [[sample totalEnergyBurned] doubleValueForUnit:[HKUnit kilocalorieUnit]];
                        double distance = [[sample totalDistance] doubleValueForUnit:[HKUnit mileUnit]];
                        NSString *type = [RCTAppleHealthKit stringForHKWorkoutActivityType:[sample workoutActivityType]];
241

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

245
                        bool isTracked = true;
246 247 248
                        if ([[sample metadata][HKMetadataKeyWasUserEntered] intValue] == 1) {
                            isTracked = false;
                        }
249

250 251 252 253 254 255 256 257 258
                        NSString* device = @"";
                        if (@available(iOS 11.0, *)) {
                            device = [[sample sourceRevision] productType];
                        } else {
                            device = [[sample device] name];
                            if (!device) {
                                device = @"iPhone";
                            }
                        }
259

260
                        NSDictionary *elem = @{
261 262
                                               @"activityId" : [NSNumber numberWithInt:[sample workoutActivityType]],
                                               @"activityName" : type,
Evgenii Evstropov's avatar
Evgenii Evstropov committed
263 264
                                               @"calories" : @(energy),
                                               @"tracked" : @(isTracked),
265
                                               @"sourceName" : [[[sample sourceRevision] source] name],
Evgenii Evstropov's avatar
Evgenii Evstropov committed
266
                                               @"sourceId" : [[[sample sourceRevision] source] bundleIdentifier],
267
                                               @"device": device,
268
                                               @"distance" : @(distance),
Evgenii Evstropov's avatar
Evgenii Evstropov committed
269 270
                                               @"start" : startDateString,
                                               @"end" : endDateString
271
                                               };
272

273 274 275 276 277 278
                        [data addObject:elem];
                    }
                } else {
                    for (HKQuantitySample *sample in results) {
                        HKQuantity *quantity = sample.quantity;
                        double value = [quantity doubleValueForUnit:unit];
279

280 281 282 283
                        NSString * valueType = @"quantity";
                        if (unit == [HKUnit mileUnit]) {
                            valueType = @"distance";
                        }
284

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

288
                        bool isTracked = true;
289 290 291
                        if ([[sample metadata][HKMetadataKeyWasUserEntered] intValue] == 1) {
                            isTracked = false;
                        }
292

Adam Ivancza's avatar
Adam Ivancza committed
293 294 295 296 297 298 299 300 301
                        NSString* device = @"";
                        if (@available(iOS 11.0, *)) {
                            device = [[sample sourceRevision] productType];
                        } else {
                            device = [[sample device] name];
                            if (!device) {
                                device = @"iPhone";
                            }
                        }
302

303
                        NSDictionary *elem = @{
304
                                               valueType : @(value),
Evgenii Evstropov's avatar
Evgenii Evstropov committed
305
                                               @"tracked" : @(isTracked),
306
                                               @"sourceName" : [[[sample sourceRevision] source] name],
Evgenii Evstropov's avatar
Evgenii Evstropov committed
307
                                               @"sourceId" : [[[sample sourceRevision] source] bundleIdentifier],
Adam Ivancza's avatar
Adam Ivancza committed
308
                                               @"device": device,
Evgenii Evstropov's avatar
Evgenii Evstropov committed
309 310
                                               @"start" : startDateString,
                                               @"end" : endDateString
311
                                               };
312

313 314
                        [data addObject:elem];
                    }
EEvgeniiF's avatar
EEvgeniiF committed
315
                }
316

EEvgeniiF's avatar
EEvgeniiF committed
317 318 319 320
                completion(data, error);
            });
        }
    };
321

322
    HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:type
EEvgeniiF's avatar
EEvgeniiF committed
323 324 325 326
                                                           predicate:predicate
                                                               limit:lim
                                                     sortDescriptors:@[timeSortDescriptor]
                                                      resultsHandler:handlerBlock];
327

EEvgeniiF's avatar
EEvgeniiF committed
328 329
    [self.healthStore executeQuery:query];
}
330 331


Evgenii Evstropov's avatar
Evgenii Evstropov committed
332
- (void)setObserverForType:(HKSampleType *)type
333 334
                      unit:(HKUnit *)unit {
    HKObserverQuery *query = [[HKObserverQuery alloc] initWithSampleType:type predicate:nil updateHandler:^(HKObserverQuery *query, HKObserverQueryCompletionHandler completionHandler, NSError * _Nullable error){
335 336 337 338 339
        if (error) {
            NSLog(@"*** An error occured while setting up the stepCount observer. %@ ***", error.localizedDescription);
            return;
        }
        [self.bridge.eventDispatcher sendAppEventWithName:@"observer" body:@""];
340

341 342
        // Theoretically, HealthKit expect that copletionHandler would be called at the end of query process,
        // but it's unclear how to do in in event paradigm
343

344 345
//        dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 5);
//        dispatch_after(delay, dispatch_get_main_queue(), ^(void){
346
//            completionHandler();
347
//        });
348
    }];
349

Evgenii Evstropov's avatar
Evgenii Evstropov committed
350 351 352 353 354
    [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]);
    }];
}
355 356 357 358 359 360

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

    NSSortDescriptor *timeSortDescriptor = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierEndDate
王品堯's avatar
王品堯 committed
361
                                                                       ascending:true];
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381


    // 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) {

382
                    // HKCategoryType *catType = sample.categoryType;
383
                    NSInteger val = sample.value;
384

王品堯's avatar
王品堯 committed
385 386
                    int startDateTimestamp = [RCTAppleHealthKit buildTimestampFromDate:sample.startDate];
                    int endDateTimestamp = [RCTAppleHealthKit buildTimestampFromDate:sample.endDate];
387

王品堯's avatar
王品堯 committed
388
                    NSString *valueString = [NSString stringWithFormat:@"%d", val];
389 390 391 392 393 394 395 396 397 398 399
                    
                    NSString *deviceName = sample.device.name ? sample.device.name : @"";
                    NSString *deviceManufacturer = sample.device.manufacturer ? sample.device.manufacturer : @"";
                    NSString *deviceHardwareVer = sample.device.hardwareVersion ? sample.device.hardwareVersion : @"";
                    NSString *deviceSoftwareVer = sample.device.softwareVersion ? sample.device.softwareVersion : @"";
                    
                    NSString *sourceName = sample.sourceRevision.source.name;
                    NSString *sourceId = sample.sourceRevision.source.bundleIdentifier;
                    
                    NSString *uuid = sample.UUID.UUIDString;
                    
王品堯's avatar
王品堯 committed
400 401 402
                    NSString *metadata = [sample.metadata == nil ? @"" : sample.metadata.description stringByReplacingOccurrencesOfString:@" " withString:@""];
                    metadata = [metadata stringByReplacingOccurrencesOfString:@"\r" withString:@""];
                    metadata = [metadata stringByReplacingOccurrencesOfString:@"\n" withString:@""];
403

404
                    NSDictionary *elem = @{
405
                            @"value" : valueString,
王品堯's avatar
王品堯 committed
406 407
                            @"startDate" : @(startDateTimestamp),
                            @"endDate" : @(endDateTimestamp),
408 409 410 411 412 413 414 415
                            @"deviceName" : deviceName,
                            @"deviceManufacturer" : deviceManufacturer,
                            @"deviceHardware" : deviceHardwareVer,
                            @"deviceSoftware" : deviceSoftwareVer,
                            @"sourceName" : sourceName,
                            @"sourceId" : sourceId,
                            @"uuid" : uuid,
                            @"metadata" : metadata
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
                    };

                    [data addObject:elem];
                }

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

    HKCategoryType *categoryType =
    [HKObjectType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis];

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


    [self.healthStore executeQuery:query];
}


440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
- (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;
        }
460

461 462 463 464 465 466
        if (completion) {
            NSMutableArray *data = [NSMutableArray arrayWithCapacity:1];

            dispatch_async(dispatch_get_main_queue(), ^{

                for (HKCorrelation *sample in results) {
王品堯's avatar
王品堯 committed
467 468
                    int startDateTimestamp = [RCTAppleHealthKit buildTimestampFromDate:sample.startDate];
                    int endDateTimestamp = [RCTAppleHealthKit buildTimestampFromDate:sample.endDate];
469 470

                    NSDictionary *elem = @{
Greg Wilson's avatar
Greg Wilson committed
471
                      @"correlation" : sample,
王品堯's avatar
王品堯 committed
472 473
                      @"startDate" : @(startDateTimestamp),
                      @"endDate" : @(endDateTimestamp),
Greg Wilson's avatar
Greg Wilson committed
474
                    };
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
                    [data addObject:elem];
                }

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

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

    [self.healthStore executeQuery:query];
}
491 492


493 494 495 496
- (void)fetchSumOfSamplesTodayForType:(HKQuantityType *)quantityType
                                 unit:(HKUnit *)unit
                           completion:(void (^)(double, NSError *))completionHandler {

497
    NSPredicate *predicate = [RCTAppleHealthKit predicateForSamplesToday];
498 499 500 501
    HKStatisticsQuery *query = [[HKStatisticsQuery alloc] initWithQuantityType:quantityType
                                                          quantitySamplePredicate:predicate
                                                          options:HKStatisticsOptionCumulativeSum
                                                          completionHandler:^(HKStatisticsQuery *query, HKStatistics *result, NSError *error) {
502 503 504 505 506 507
                                                                HKQuantity *sum = [result sumQuantity];
                                                                if (completionHandler) {
                                                                    double value = [sum doubleValueForUnit:unit];
                                                                    completionHandler(value, error);
                                                                }
                                                          }];
Greg Wilson's avatar
Greg Wilson committed
508

509 510 511
    [self.healthStore executeQuery:query];
}

512

513 514 515
- (void)fetchSumOfSamplesOnDayForType:(HKQuantityType *)quantityType
                                 unit:(HKUnit *)unit
                                  day:(NSDate *)day
516
                           completion:(void (^)(double, NSDate *, NSDate *, NSError *))completionHandler {
517

518
    NSPredicate *predicate = [RCTAppleHealthKit predicateForSamplesOnDay:day];
519
    HKStatisticsQuery *query = [[HKStatisticsQuery alloc] initWithQuantityType:quantityType
520 521 522 523
                                                          quantitySamplePredicate:predicate
                                                          options:HKStatisticsOptionCumulativeSum
                                                          completionHandler:^(HKStatisticsQuery *query, HKStatistics *result, NSError *error) {
                                                              HKQuantity *sum = [result sumQuantity];
524 525
                                                              NSDate *startDate = result.startDate;
                                                              NSDate *endDate = result.endDate;
526
                                                              if (completionHandler) {
527
                                                                     double value = [sum doubleValueForUnit:unit];
528
                                                                     completionHandler(value,startDate, endDate, error);
529 530
                                                              }
                                                          }];
531 532 533 534 535

    [self.healthStore executeQuery:query];
}


536 537 538 539
- (void)fetchCumulativeSumStatisticsCollection:(HKQuantityType *)quantityType
                                          unit:(HKUnit *)unit
                                     startDate:(NSDate *)startDate
                                       endDate:(NSDate *)endDate
540
                                    completion:(void (^)(NSArray *, NSError *))completionHandler {
541 542 543 544 545 546 547 548 549

    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];
550
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"metadata.%K != YES", HKMetadataKeyWasUserEntered];
551
    // Create the query
552
    HKStatisticsCollectionQuery *query = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:quantityType
553
                                                                           quantitySamplePredicate:predicate
554 555 556 557
                                                                                           options:HKStatisticsOptionCumulativeSum
                                                                                        anchorDate:anchorDate
                                                                                intervalComponents:interval];

558
    // Set the results handler
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
    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];
}


589 590 591 592 593 594
- (void)fetchCumulativeSumStatisticsCollection:(HKQuantityType *)quantityType
                                          unit:(HKUnit *)unit
                                     startDate:(NSDate *)startDate
                                       endDate:(NSDate *)endDate
                                     ascending:(BOOL)asc
                                         limit:(NSUInteger)lim
595
                                           gap:(NSString *)gap
596
                          includeManuallyAdded:(BOOL)includeManuallyAdded
597 598 599 600
                                    completion:(void (^)(NSArray *, NSError *))completionHandler {

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *interval = [[NSDateComponents alloc] init];
601 602 603 604 605
    if([gap isEqual: @"hour"]){
        interval.hour = 1;
    }else {
        interval.day = 1;
    }
606 607 608 609 610

    NSDateComponents *anchorComponents = [calendar components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear
                                                     fromDate:[NSDate date]];
    anchorComponents.hour = 0;
    NSDate *anchorDate = [calendar dateFromComponents:anchorComponents];
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"metadata.%K != YES", HKMetadataKeyWasUserEntered];
    // Create the query
    HKStatisticsCollectionQuery *query = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:quantityType
                                                                           quantitySamplePredicate:predicate
                                                                                           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) {
            [RCTAppleHealthKit reverseNSMutableArray:data];
        }

        if((lim > 0) && ([data count] > lim)) {
            NSArray* slicedArray = [data subarrayWithRange:NSMakeRange(0, lim)];
            NSError *err;
            completionHandler(slicedArray, err);
        } else {
            NSError *err;
            completionHandler(data, err);
        }
    };

    [self.healthStore executeQuery:query];
}

667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
- (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];
683
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"metadata.%K != YES", HKMetadataKeyWasUserEntered];
684 685
    // Create the query
    HKStatisticsCollectionQuery *query = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:quantityType
686
                                                                           quantitySamplePredicate:predicate
687 688 689
                                                                                           options:HKStatisticsOptionCumulativeSum
                                                                                        anchorDate:anchorDate
                                                                                intervalComponents:interval];
690

691 692 693 694 695 696 697 698
    // 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];
699

700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
        [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) {
            [RCTAppleHealthKit reverseNSMutableArray:data];
        }

        if((lim > 0) && ([data count] > lim)) {
            NSArray* slicedArray = [data subarrayWithRange:NSMakeRange(0, lim)];
            NSError *err;
            completionHandler(slicedArray, err);
        } else {
            NSError *err;
            completionHandler(data, err);
        }
    };

    [self.healthStore executeQuery:query];
}

- (void)fetchCumulativeSumStatisticsCollection:(HKQuantityType *)quantityType
                                          unit:(HKUnit *)unit
                                          period:(NSUInteger)period
                                     startDate:(NSDate *)startDate
                                       endDate:(NSDate *)endDate
                                     ascending:(BOOL)asc
                                         limit:(NSUInteger)lim
746
                          includeManuallyAdded:(BOOL)includeManuallyAdded
747 748 749 750 751 752
                                    completion:(void (^)(NSArray *, NSError *))completionHandler {

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *interval = [[NSDateComponents alloc] init];
    interval.minute = period;

Furyou81's avatar
Furyou81 committed
753
    NSDateComponents *anchorComponents = [calendar components:NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear
Furyou81's avatar
Furyou81 committed
754
                                                     fromDate:startDate];
Furyou81's avatar
add  
Furyou81 committed
755
    //anchorComponents.hour = 0;
756
    NSDate *anchorDate = [calendar dateFromComponents:anchorComponents];
757 758 759 760
    NSPredicate *predicate = nil;
    if (includeManuallyAdded == false) {
        predicate = [NSPredicate predicateWithFormat:@"metadata.%K != YES", HKMetadataKeyWasUserEntered];
    }
761 762
    // Create the query
    HKStatisticsCollectionQuery *query = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:quantityType
Furyou81's avatar
add  
Furyou81 committed
763
                                                                           quantitySamplePredicate:predicate
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
                                                                                           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;
王品堯's avatar
王品堯 committed
785
                                           int value = round([quantity doubleValueForUnit:unit]);
786

王品堯's avatar
王品堯 committed
787 788
                                           int startDateTimestamp = [RCTAppleHealthKit buildTimestampFromDate:startDate];
                                           int endDateTimestamp = [RCTAppleHealthKit buildTimestampFromDate:endDate];
789 790 791

                                           NSDictionary *elem = @{
                                                   @"value" : @(value),
王品堯's avatar
王品堯 committed
792 793
                                                   @"startDate" : @(startDateTimestamp),
                                                   @"endDate" : @(endDateTimestamp),
794 795 796 797 798 799
                                           };
                                           [data addObject:elem];
                                       }
                                   }];
        // is ascending by default
        if(asc == false) {
800
            [RCTAppleHealthKit reverseNSMutableArray:data];
801 802
        }

803
        if((lim > 0) && ([data count] > lim)) {
804 805 806 807 808 809 810 811 812 813 814 815
            NSArray* slicedArray = [data subarrayWithRange:NSMakeRange(0, lim)];
            NSError *err;
            completionHandler(slicedArray, err);
        } else {
            NSError *err;
            completionHandler(data, err);
        }
    };

    [self.healthStore executeQuery:query];
}

816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
- (void)fetchQuantitySamplesOfTypeByAnchor:(HKQuantityType *)quantityType
                                      unit:(HKUnit *)unit
                                 predicate:(NSPredicate *)predicate
                                 ascending:(BOOL)asc
                                     limit:(NSUInteger)lim
                                completion:(void (^)(NSDictionary *, NSError *))completion {
    
    void (^anchorHandlerBlock)(HKAnchoredObjectQuery *query, NSArray *sampleObjects, NSArray *deletedObjects, HKQueryAnchor *newAnchor, NSError *error);
    anchorHandlerBlock = ^(HKAnchoredObjectQuery *query, NSArray *sampleObjects, NSArray *deletedObjects, HKQueryAnchor *newAnchor, NSError *error) {
        if (!sampleObjects && !deletedObjects) {
            if (completion) {
                completion(nil, error);
            }
            return;
        }
        
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:newAnchor];
833
        [[NSUserDefaults standardUserDefaults] setObject:data forKey:[RCTAppleHealthKit stringFromType:quantityType status:false]];
834 835 836 837 838 839 840 841 842 843 844
        
        if (completion) {
            NSMutableArray *data = [NSMutableArray arrayWithCapacity:1];
            NSMutableArray *removeData = [NSMutableArray arrayWithCapacity:1];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                for (HKQuantitySample *sample in sampleObjects) {
                    HKQuantity *quantity = sample.quantity;
                    double value = [quantity doubleValueForUnit:unit];
                    
王品堯's avatar
王品堯 committed
845 846
                    int startDateTimestamp = [RCTAppleHealthKit buildTimestampFromDate:sample.startDate];
                    int endDateTimestamp = [RCTAppleHealthKit buildTimestampFromDate:sample.endDate];
847 848 849 850 851 852 853 854 855 856 857
                    
                    NSString *deviceName = sample.device.name ? sample.device.name : @"";
                    NSString *deviceManufacturer = sample.device.manufacturer ? sample.device.manufacturer : @"";
                    NSString *deviceHardwareVer = sample.device.hardwareVersion ? sample.device.hardwareVersion : @"";
                    NSString *deviceSoftwareVer = sample.device.softwareVersion ? sample.device.softwareVersion : @"";
                    
                    NSString *sourceName = sample.sourceRevision.source.name;
                    NSString *sourceId = sample.sourceRevision.source.bundleIdentifier;
                    
                    NSString *uuid = sample.UUID.UUIDString;
                    
王品堯's avatar
王品堯 committed
858 859 860
                    NSString *metadata = [sample.metadata == nil ? @"" : sample.metadata.description stringByReplacingOccurrencesOfString:@" " withString:@""];
                    metadata = [metadata stringByReplacingOccurrencesOfString:@"\r" withString:@""];
                    metadata = [metadata stringByReplacingOccurrencesOfString:@"\n" withString:@""];
861 862 863
                    
                    NSDictionary *elem = @{
                                           @"value" : @(value),
王品堯's avatar
王品堯 committed
864 865
                                           @"startDate" : @(startDateTimestamp),
                                           @"endDate" : @(endDateTimestamp),
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
                                           @"deviceName" : deviceName,
                                           @"deviceManufacturer" : deviceManufacturer,
                                           @"deviceHardware" : deviceHardwareVer,
                                           @"deviceSoftware" : deviceSoftwareVer,
                                           @"sourceName" : sourceName,
                                           @"sourceId" : sourceId,
                                           @"unit" : unit.description,
                                           @"uuid" : uuid,
                                           @"metadata" : metadata
                                           };
                    
                    [data addObject:elem];
                }
                
                for (HKDeletedObject *sample in deletedObjects) {
                    [removeData addObject:sample.UUID.UUIDString];
                }
                
                NSDictionary *result = @{
                                         @"samples" : data,
                                         @"deleteSamples" : removeData
                                         };
                
                completion(result, error);
            });
        }
    };
    
894
    NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:[RCTAppleHealthKit stringFromType:quantityType status:true]];
895 896 897
    HKQueryAnchor *anchor = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    
    HKAnchoredObjectQuery *anchorQuery = [[HKAnchoredObjectQuery alloc] initWithType:quantityType
898
                                                                           predicate:nil
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921
                                                                              anchor:anchor
                                                                               limit:lim
                                                                      resultsHandler:anchorHandlerBlock];
    [self.healthStore executeQuery:anchorQuery];
}

- (void)fetchCorrelationSamplesOfTypeByAnchor:(HKQuantityType *)quantityType
                                         unit:(HKUnit *)unit
                                    predicate:(NSPredicate *)predicate
                                    ascending:(BOOL)asc
                                        limit:(NSUInteger)lim
                                   completion:(void (^)(NSDictionary *, NSError *))completion
{
    void (^anchorHandlerBlock)(HKAnchoredObjectQuery *query, NSArray *sampleObjects, NSArray *deletedObjects, HKQueryAnchor *newAnchor, NSError *error);
    anchorHandlerBlock = ^(HKAnchoredObjectQuery *query, NSArray *sampleObjects, NSArray *deletedObjects, HKQueryAnchor *newAnchor, NSError *error) {
        if (!sampleObjects && !deletedObjects) {
            if (completion) {
                completion(nil, error);
            }
            return;
        }
        
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:newAnchor];
922
        [[NSUserDefaults standardUserDefaults] setObject:data forKey:[RCTAppleHealthKit stringFromType:quantityType status:false]];
923 924 925 926 927 928 929 930
        
        if (completion) {
            NSMutableArray *data = [NSMutableArray arrayWithCapacity:1];
            NSMutableArray *removeData = [NSMutableArray arrayWithCapacity:1];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                for (HKCorrelation *sample in sampleObjects) {
王品堯's avatar
王品堯 committed
931 932 933
                    int startDateTimestamp = [RCTAppleHealthKit buildTimestampFromDate:sample.startDate];
                    int endDateTimestamp = [RCTAppleHealthKit buildTimestampFromDate:sample.endDate];

934 935
                    NSDictionary *elem = @{
                                           @"correlation" : sample,
王品堯's avatar
王品堯 committed
936 937
                                           @"startDate" : @(startDateTimestamp),
                                           @"endDate" : @(endDateTimestamp),
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
                                           };
                    [data addObject:elem];
                }
                
                for (HKDeletedObject *sample in deletedObjects) {
                    [removeData addObject:sample.UUID.UUIDString];
                }
                
                NSDictionary *result = @{
                                         @"samples" : data,
                                         @"deleteSamples" : removeData
                                         };
                
                completion(result, error);
            });
        }
    };
    
956
    NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:[RCTAppleHealthKit stringFromType:quantityType status:true]];
957 958 959
    HKQueryAnchor *anchor = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    
    HKAnchoredObjectQuery *anchorQuery = [[HKAnchoredObjectQuery alloc] initWithType:quantityType
960
                                                                           predicate:nil
961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
                                                                              anchor:anchor
                                                                               limit:lim
                                                                      resultsHandler:anchorHandlerBlock];
    
    [self.healthStore executeQuery:anchorQuery];
}

- (void)fetchSleepCategorySamplesForPredicateByAnchor:(NSPredicate *)predicate
                                                limit:(NSUInteger)lim
                                           completion:(void (^)(NSDictionary *, NSError *))completion
{
    HKCategoryType *categoryType = [HKObjectType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis];
    
    void (^anchorHandlerBlock)(HKAnchoredObjectQuery *query, NSArray *sampleObjects, NSArray *deletedObjects, HKQueryAnchor *newAnchor, NSError *error);
    anchorHandlerBlock = ^(HKAnchoredObjectQuery *query, NSArray *sampleObjects, NSArray *deletedObjects, HKQueryAnchor *newAnchor, NSError *error) {
        if (!sampleObjects && !deletedObjects) {
            if (completion) {
                completion(nil, error);
            }
            return;
        }
        
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:newAnchor];
984
        [[NSUserDefaults standardUserDefaults] setObject:data forKey:[RCTAppleHealthKit stringFromType:categoryType status:false]];
985 986 987 988 989 990 991 992 993 994
        
        if (completion) {
            NSMutableArray *data = [NSMutableArray arrayWithCapacity:1];
            NSMutableArray *removeData = [NSMutableArray arrayWithCapacity:1];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                for (HKCategorySample *sample in sampleObjects) {
                    NSInteger val = sample.value;
                    
王品堯's avatar
王品堯 committed
995 996
                    int startDateTimestamp = [RCTAppleHealthKit buildTimestampFromDate:sample.startDate];
                    int endDateTimestamp = [RCTAppleHealthKit buildTimestampFromDate:sample.endDate];
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
                    
                    NSString *valueString = [NSString stringWithFormat:@"%d", val];
                    
                    NSString *deviceName = sample.device.name ? sample.device.name : @"";
                    NSString *deviceManufacturer = sample.device.manufacturer ? sample.device.manufacturer : @"";
                    NSString *deviceHardwareVer = sample.device.hardwareVersion ? sample.device.hardwareVersion : @"";
                    NSString *deviceSoftwareVer = sample.device.softwareVersion ? sample.device.softwareVersion : @"";
                    
                    NSString *sourceName = sample.sourceRevision.source.name;
                    NSString *sourceId = sample.sourceRevision.source.bundleIdentifier;
                    
                    NSString *uuid = sample.UUID.UUIDString;
                    
王品堯's avatar
王品堯 committed
1010 1011 1012
                    NSString *metadata = [sample.metadata == nil ? @"" : sample.metadata.description stringByReplacingOccurrencesOfString:@" " withString:@""];
                    metadata = [metadata stringByReplacingOccurrencesOfString:@"\r" withString:@""];
                    metadata = [metadata stringByReplacingOccurrencesOfString:@"\n" withString:@""];
1013 1014 1015
                    
                    NSDictionary *elem = @{
                                           @"value" : valueString,
王品堯's avatar
王品堯 committed
1016 1017
                                           @"startDate" : @(startDateTimestamp),
                                           @"endDate" : @(endDateTimestamp),
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
                                           @"deviceName" : deviceName,
                                           @"deviceManufacturer" : deviceManufacturer,
                                           @"deviceHardware" : deviceHardwareVer,
                                           @"deviceSoftware" : deviceSoftwareVer,
                                           @"sourceName" : sourceName,
                                           @"sourceId" : sourceId,
                                           @"uuid" : uuid,
                                           @"metadata" : metadata
                                           };
                    
                    [data addObject:elem];
                }
                
                for (HKDeletedObject *sample in deletedObjects) {
                    [removeData addObject:sample.UUID.UUIDString];
                }
                
                NSDictionary *result = @{
                                         @"samples" : data,
                                         @"deleteSamples" : removeData
                                         };
                
                completion(result, error);
            });
        }
    };
    
1045
    NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:[RCTAppleHealthKit stringFromType:categoryType status:true]];
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
    HKQueryAnchor *anchor = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    
    HKAnchoredObjectQuery *anchorQuery = [[HKAnchoredObjectQuery alloc] initWithType:categoryType
                                                                           predicate:predicate
                                                                              anchor:anchor
                                                                               limit:lim
                                                                      resultsHandler:anchorHandlerBlock];
    
    [self.healthStore executeQuery:anchorQuery];
}

1057
@end