RCTAppleHealthKit+Queries.m 38.7 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 16 17
- (void)fetchMostRecentQuantitySampleOfType:(HKQuantityType *)quantityType
                                  predicate:(NSPredicate *)predicate
                                 completion:(void (^)(HKQuantity *, NSDate *, NSDate *, NSError *))completion {
18

19 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
    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);
                      }
                }
    ];
48 49 50 51
    [self.healthStore executeQuery:query];
}


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

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

76
            dispatch_async(dispatch_get_main_queue(), ^{
77

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

王品堯's avatar
王品堯 committed
82 83
                    int startDateTimestamp = [RCTAppleHealthKit buildTimestampFromDate:sample.startDate];
                    int endDateTimestamp = [RCTAppleHealthKit buildTimestampFromDate:sample.endDate];
84 85 86 87 88 89 90 91 92 93 94
                    
                    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
95 96 97
                    NSString *metadata = [sample.metadata == nil ? @"" : sample.metadata.description stringByReplacingOccurrencesOfString:@" " withString:@""];
                    metadata = [metadata stringByReplacingOccurrencesOfString:@"\r" withString:@""];
                    metadata = [metadata stringByReplacingOccurrencesOfString:@"\n" withString:@""];
98
                    
99 100
                    NSDictionary *elem = @{
                            @"value" : @(value),
王品堯's avatar
王品堯 committed
101 102
                            @"startDate" : @(startDateTimestamp),
                            @"endDate" : @(endDateTimestamp),
103 104 105 106 107 108 109 110 111
                            @"deviceName" : deviceName,
                            @"deviceManufacturer" : deviceManufacturer,
                            @"deviceHardware" : deviceHardwareVer,
                            @"deviceSoftware" : deviceSoftwareVer,
                            @"sourceName" : sourceName,
                            @"sourceId" : sourceId,
                            @"unit" : unit.description,
                            @"uuid" : uuid,
                            @"metadata" : metadata
112
                    };
113

114 115
                    [data addObject:elem];
                }
116

117 118 119 120
                completion(data, error);
            });
        }
    };
121

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

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


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 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
- (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];
}
210 211 212 213 214 215 216 217 218 219 220 221 222







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


    NSSortDescriptor *timeSortDescriptor = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierEndDate
王品堯's avatar
王品堯 committed
223
                                                                       ascending:true];
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243


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

244
                    // HKCategoryType *catType = sample.categoryType;
245
                    NSInteger val = sample.value;
246

王品堯's avatar
王品堯 committed
247 248
                    int startDateTimestamp = [RCTAppleHealthKit buildTimestampFromDate:sample.startDate];
                    int endDateTimestamp = [RCTAppleHealthKit buildTimestampFromDate:sample.endDate];
249

王品堯's avatar
王品堯 committed
250
                    NSString *valueString = [NSString stringWithFormat:@"%d", val];
251 252 253 254 255 256 257 258 259 260 261
                    
                    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
262 263 264
                    NSString *metadata = [sample.metadata == nil ? @"" : sample.metadata.description stringByReplacingOccurrencesOfString:@" " withString:@""];
                    metadata = [metadata stringByReplacingOccurrencesOfString:@"\r" withString:@""];
                    metadata = [metadata stringByReplacingOccurrencesOfString:@"\n" withString:@""];
265

266
                    NSDictionary *elem = @{
267
                            @"value" : valueString,
王品堯's avatar
王品堯 committed
268 269
                            @"startDate" : @(startDateTimestamp),
                            @"endDate" : @(endDateTimestamp),
270 271 272 273 274 275 276 277
                            @"deviceName" : deviceName,
                            @"deviceManufacturer" : deviceManufacturer,
                            @"deviceHardware" : deviceHardwareVer,
                            @"deviceSoftware" : deviceSoftwareVer,
                            @"sourceName" : sourceName,
                            @"sourceId" : sourceId,
                            @"uuid" : uuid,
                            @"metadata" : metadata
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
                    };

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


302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
- (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;
        }
322

323 324 325 326 327 328
        if (completion) {
            NSMutableArray *data = [NSMutableArray arrayWithCapacity:1];

            dispatch_async(dispatch_get_main_queue(), ^{

                for (HKCorrelation *sample in results) {
王品堯's avatar
王品堯 committed
329 330
                    int startDateTimestamp = [RCTAppleHealthKit buildTimestampFromDate:sample.startDate];
                    int endDateTimestamp = [RCTAppleHealthKit buildTimestampFromDate:sample.endDate];
331 332

                    NSDictionary *elem = @{
Greg Wilson's avatar
Greg Wilson committed
333
                      @"correlation" : sample,
王品堯's avatar
王品堯 committed
334 335
                      @"startDate" : @(startDateTimestamp),
                      @"endDate" : @(endDateTimestamp),
Greg Wilson's avatar
Greg Wilson committed
336
                    };
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
                    [data addObject:elem];
                }

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

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

    [self.healthStore executeQuery:query];
}
353 354


355 356 357 358
- (void)fetchSumOfSamplesTodayForType:(HKQuantityType *)quantityType
                                 unit:(HKUnit *)unit
                           completion:(void (^)(double, NSError *))completionHandler {

359
    NSPredicate *predicate = [RCTAppleHealthKit predicateForSamplesToday];
360 361 362 363
    HKStatisticsQuery *query = [[HKStatisticsQuery alloc] initWithQuantityType:quantityType
                                                          quantitySamplePredicate:predicate
                                                          options:HKStatisticsOptionCumulativeSum
                                                          completionHandler:^(HKStatisticsQuery *query, HKStatistics *result, NSError *error) {
364 365 366 367 368 369
                                                                HKQuantity *sum = [result sumQuantity];
                                                                if (completionHandler) {
                                                                    double value = [sum doubleValueForUnit:unit];
                                                                    completionHandler(value, error);
                                                                }
                                                          }];
Greg Wilson's avatar
Greg Wilson committed
370

371 372 373
    [self.healthStore executeQuery:query];
}

374

375 376 377
- (void)fetchSumOfSamplesOnDayForType:(HKQuantityType *)quantityType
                                 unit:(HKUnit *)unit
                                  day:(NSDate *)day
378
                           completion:(void (^)(double, NSDate *, NSDate *, NSError *))completionHandler {
379

380
    NSPredicate *predicate = [RCTAppleHealthKit predicateForSamplesOnDay:day];
381
    HKStatisticsQuery *query = [[HKStatisticsQuery alloc] initWithQuantityType:quantityType
382 383 384 385
                                                          quantitySamplePredicate:predicate
                                                          options:HKStatisticsOptionCumulativeSum
                                                          completionHandler:^(HKStatisticsQuery *query, HKStatistics *result, NSError *error) {
                                                              HKQuantity *sum = [result sumQuantity];
386 387
                                                              NSDate *startDate = result.startDate;
                                                              NSDate *endDate = result.endDate;
388
                                                              if (completionHandler) {
389
                                                                     double value = [sum doubleValueForUnit:unit];
390
                                                                     completionHandler(value,startDate, endDate, error);
391 392
                                                              }
                                                          }];
393 394 395 396 397

    [self.healthStore executeQuery:query];
}


398 399 400 401
- (void)fetchCumulativeSumStatisticsCollection:(HKQuantityType *)quantityType
                                          unit:(HKUnit *)unit
                                     startDate:(NSDate *)startDate
                                       endDate:(NSDate *)endDate
402
                                    completion:(void (^)(NSArray *, NSError *))completionHandler {
403 404 405 406 407 408 409 410 411 412

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

413
    // Create the query
414 415 416 417 418 419
    HKStatisticsCollectionQuery *query = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:quantityType
                                                                           quantitySamplePredicate:nil
                                                                                           options:HKStatisticsOptionCumulativeSum
                                                                                        anchorDate:anchorDate
                                                                                intervalComponents:interval];

420
    // Set the results handler
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
    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];
}


451 452 453 454 455 456
- (void)fetchCumulativeSumStatisticsCollection:(HKQuantityType *)quantityType
                                          unit:(HKUnit *)unit
                                     startDate:(NSDate *)startDate
                                       endDate:(NSDate *)endDate
                                     ascending:(BOOL)asc
                                         limit:(NSUInteger)lim
457
                                           gap:(NSString *)gap
458 459 460 461
                                    completion:(void (^)(NSArray *, NSError *))completionHandler {

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *interval = [[NSDateComponents alloc] init];
462 463 464 465 466
    if([gap isEqual: @"hour"]){
        interval.hour = 1;
    }else {
        interval.day = 1;
    }
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496

    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;
王品堯's avatar
王品堯 committed
497
                                           int value = round([quantity doubleValueForUnit:unit]);
498

王品堯's avatar
王品堯 committed
499 500
                                           int startDateTimestamp = [RCTAppleHealthKit buildTimestampFromDate:startDate];
                                           int endDateTimestamp = [RCTAppleHealthKit buildTimestampFromDate:endDate];
501 502 503

                                           NSDictionary *elem = @{
                                                   @"value" : @(value),
王品堯's avatar
王品堯 committed
504 505
                                                   @"startDate" : @(startDateTimestamp),
                                                   @"endDate" : @(endDateTimestamp),
506 507 508 509 510 511
                                           };
                                           [data addObject:elem];
                                       }
                                   }];
        // is ascending by default
        if(asc == false) {
512
            [RCTAppleHealthKit reverseNSMutableArray:data];
513 514
        }

515
        if((lim > 0) && ([data count] > lim)) {
516 517 518 519 520 521 522 523 524 525 526 527
            NSArray* slicedArray = [data subarrayWithRange:NSMakeRange(0, lim)];
            NSError *err;
            completionHandler(slicedArray, err);
        } else {
            NSError *err;
            completionHandler(data, err);
        }
    };

    [self.healthStore executeQuery:query];
}

528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
- (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];
545
        [[NSUserDefaults standardUserDefaults] setObject:data forKey:[RCTAppleHealthKit stringFromType:quantityType status:false]];
546 547 548 549 550 551 552 553 554 555 556
        
        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
557 558
                    int startDateTimestamp = [RCTAppleHealthKit buildTimestampFromDate:sample.startDate];
                    int endDateTimestamp = [RCTAppleHealthKit buildTimestampFromDate:sample.endDate];
559 560 561 562 563 564 565 566 567 568 569
                    
                    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
570 571 572
                    NSString *metadata = [sample.metadata == nil ? @"" : sample.metadata.description stringByReplacingOccurrencesOfString:@" " withString:@""];
                    metadata = [metadata stringByReplacingOccurrencesOfString:@"\r" withString:@""];
                    metadata = [metadata stringByReplacingOccurrencesOfString:@"\n" withString:@""];
573 574 575
                    
                    NSDictionary *elem = @{
                                           @"value" : @(value),
王品堯's avatar
王品堯 committed
576 577
                                           @"startDate" : @(startDateTimestamp),
                                           @"endDate" : @(endDateTimestamp),
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
                                           @"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);
            });
        }
    };
    
606
    NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:[RCTAppleHealthKit stringFromType:quantityType status:true]];
607 608 609
    HKQueryAnchor *anchor = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    
    HKAnchoredObjectQuery *anchorQuery = [[HKAnchoredObjectQuery alloc] initWithType:quantityType
610
                                                                           predicate:nil
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
                                                                              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];
634
        [[NSUserDefaults standardUserDefaults] setObject:data forKey:[RCTAppleHealthKit stringFromType:quantityType status:false]];
635 636 637 638 639 640 641 642
        
        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
643 644 645
                    int startDateTimestamp = [RCTAppleHealthKit buildTimestampFromDate:sample.startDate];
                    int endDateTimestamp = [RCTAppleHealthKit buildTimestampFromDate:sample.endDate];

646 647
                    NSDictionary *elem = @{
                                           @"correlation" : sample,
王品堯's avatar
王品堯 committed
648 649
                                           @"startDate" : @(startDateTimestamp),
                                           @"endDate" : @(endDateTimestamp),
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
                                           };
                    [data addObject:elem];
                }
                
                for (HKDeletedObject *sample in deletedObjects) {
                    [removeData addObject:sample.UUID.UUIDString];
                }
                
                NSDictionary *result = @{
                                         @"samples" : data,
                                         @"deleteSamples" : removeData
                                         };
                
                completion(result, error);
            });
        }
    };
    
668
    NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:[RCTAppleHealthKit stringFromType:quantityType status:true]];
669 670 671
    HKQueryAnchor *anchor = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    
    HKAnchoredObjectQuery *anchorQuery = [[HKAnchoredObjectQuery alloc] initWithType:quantityType
672
                                                                           predicate:nil
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
                                                                              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];
696
        [[NSUserDefaults standardUserDefaults] setObject:data forKey:[RCTAppleHealthKit stringFromType:categoryType status:false]];
697 698 699 700 701 702 703 704 705 706
        
        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
707 708
                    int startDateTimestamp = [RCTAppleHealthKit buildTimestampFromDate:sample.startDate];
                    int endDateTimestamp = [RCTAppleHealthKit buildTimestampFromDate:sample.endDate];
709 710 711 712 713 714 715 716 717 718 719 720 721
                    
                    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
722 723 724
                    NSString *metadata = [sample.metadata == nil ? @"" : sample.metadata.description stringByReplacingOccurrencesOfString:@" " withString:@""];
                    metadata = [metadata stringByReplacingOccurrencesOfString:@"\r" withString:@""];
                    metadata = [metadata stringByReplacingOccurrencesOfString:@"\n" withString:@""];
725 726 727
                    
                    NSDictionary *elem = @{
                                           @"value" : valueString,
王品堯's avatar
王品堯 committed
728 729
                                           @"startDate" : @(startDateTimestamp),
                                           @"endDate" : @(endDateTimestamp),
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
                                           @"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);
            });
        }
    };
    
757
    NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:[RCTAppleHealthKit stringFromType:categoryType status:true]];
758 759 760 761 762 763 764 765 766 767 768
    HKQueryAnchor *anchor = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    
    HKAnchoredObjectQuery *anchorQuery = [[HKAnchoredObjectQuery alloc] initWithType:categoryType
                                                                           predicate:predicate
                                                                              anchor:anchor
                                                                               limit:lim
                                                                      resultsHandler:anchorHandlerBlock];
    
    [self.healthStore executeQuery:anchorQuery];
}

769
@end