react-native-visit-rn-sdk 3.0.10 → 3.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -55,27 +55,6 @@ RCT_REMAP_METHOD(multiply,
55
55
  return @[@"EventReminder"];
56
56
  }
57
57
 
58
- - (NSString *)readGender
59
- {
60
- NSError *error;
61
- HKBiologicalSexObject *gen=[[VisitRnSdkViewManager sharedManager] biologicalSexWithError:&error];
62
- if (gen.biologicalSex==HKBiologicalSexMale)
63
- {
64
- return(@"Male");
65
- }
66
- else if (gen.biologicalSex==HKBiologicalSexFemale)
67
- {
68
- return (@"Female");
69
- }
70
- else if (gen.biologicalSex==HKBiologicalSexOther)
71
- {
72
- return (@"Other");
73
- }
74
- else{
75
- return (@"Not Set");
76
- }
77
- }
78
-
79
58
  - (void)fetchQuantitySamplesOfType:(HKQuantityType *)quantityType
80
59
  unit:(HKUnit *)unit
81
60
  predicate:(NSPredicate *)predicate
@@ -199,12 +178,13 @@ RCT_REMAP_METHOD(multiply,
199
178
  }];
200
179
  }
201
180
 
181
+ // Returns @[stepsData] — a one-element array whose only entry is the hourly
182
+ // step buckets. The array wrapper is retained so existing callers that read
183
+ // `[data objectAtIndex:0]` keep working.
202
184
  - (void)fetchHourlySteps:(NSDate*) endDate callback:(void(^)(NSArray*))callback{
203
185
  HKQuantityType *stepCountType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
204
- HKQuantityType *activeEnergyType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];
205
186
  NSCalendar *calendar = [NSCalendar currentCalendar];
206
187
  HKUnit *stepsUnit = [HKUnit countUnit];
207
- HKUnit *kcalUnit = [HKUnit kilocalorieUnit];
208
188
  NSDateComponents *interval = [[NSDateComponents alloc] init];
209
189
  interval.hour = 1;
210
190
  NSDate *startDate = [[NSCalendar calendarWithIdentifier:NSCalendarIdentifierISO8601] startOfDayForDate:endDate];
@@ -221,7 +201,6 @@ RCT_REMAP_METHOD(multiply,
221
201
 
222
202
  dispatch_group_t group = dispatch_group_create();
223
203
  NSMutableArray *stepsData = [NSMutableArray arrayWithCapacity:24];
224
- NSMutableArray *calorieData = [NSMutableArray arrayWithCapacity:24];
225
204
 
226
205
  dispatch_group_enter(group);
227
206
  HKStatisticsCollectionQuery *stepsQuery = [[HKStatisticsCollectionQuery alloc]
@@ -247,35 +226,12 @@ RCT_REMAP_METHOD(multiply,
247
226
  };
248
227
  [[VisitRnSdkViewManager sharedManager] executeQuery:stepsQuery];
249
228
 
250
- dispatch_group_enter(group);
251
- HKStatisticsCollectionQuery *caloriesQuery = [[HKStatisticsCollectionQuery alloc]
252
- initWithQuantityType:activeEnergyType
253
- quantitySamplePredicate:nil
254
- options:HKStatisticsOptionCumulativeSum
255
- anchorDate:anchorDate
256
- intervalComponents:interval];
257
- caloriesQuery.initialResultsHandler = ^(HKStatisticsCollectionQuery *q,
258
- HKStatisticsCollection *result,
259
- NSError *error) {
260
- if (error) {
261
- NSLog(@"fetchHourlySteps calories query error: %@", error.localizedDescription);
262
- } else {
263
- [result enumerateStatisticsFromDate:startDate toDate:endOfDay
264
- withBlock:^(HKStatistics *stat, BOOL *stop) {
265
- HKQuantity *quantity = stat.sumQuantity;
266
- int value = quantity ? (int)[quantity doubleValueForUnit:kcalUnit] : 0;
267
- [calorieData addObject:@(value)];
268
- }];
269
- }
270
- dispatch_group_leave(group);
271
- };
272
- [[VisitRnSdkViewManager sharedManager] executeQuery:caloriesQuery];
273
-
274
229
  dispatch_group_notify(group, dispatch_get_main_queue(), ^{
275
- callback(@[stepsData, calorieData]);
230
+ callback(@[stepsData]);
276
231
  });
277
232
  }
278
233
 
234
+ // Returns @[stepsData] — see fetchHourlySteps for why the array wrapper stays.
279
235
  -(void) fetchSteps:(NSString*) frequency endDate:(NSDate*) endDate days:(NSInteger) days callback:(void(^)(NSArray*))callback{
280
236
  NSDateComponents *interval = [[NSDateComponents alloc] init];
281
237
  NSDate *startDate;
@@ -317,12 +273,9 @@ RCT_REMAP_METHOD(multiply,
317
273
  NSDate *anchorDate = [self->calendar dateFromComponents:anchorComponents];
318
274
  NSLog(@"anchorDate in fetchSteps are, %@",anchorDate);
319
275
  HKQuantityType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
320
- HKQuantityType *activeEnergyType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];
321
- HKUnit *kcalUnit = [HKUnit kilocalorieUnit];
322
276
 
323
277
  dispatch_group_t group = dispatch_group_create();
324
278
  NSMutableArray *stepsData = [NSMutableArray new];
325
- NSMutableArray *calorieData = [NSMutableArray new];
326
279
 
327
280
  dispatch_group_enter(group);
328
281
  HKStatisticsCollectionQuery *stepsQuery = [[HKStatisticsCollectionQuery alloc]
@@ -349,223 +302,11 @@ RCT_REMAP_METHOD(multiply,
349
302
  };
350
303
  [[VisitRnSdkViewManager sharedManager] executeQuery:stepsQuery];
351
304
 
352
- dispatch_group_enter(group);
353
- HKStatisticsCollectionQuery *caloriesQuery = [[HKStatisticsCollectionQuery alloc]
354
- initWithQuantityType:activeEnergyType
355
- quantitySamplePredicate:nil
356
- options:HKStatisticsOptionCumulativeSum
357
- anchorDate:anchorDate
358
- intervalComponents:interval];
359
- caloriesQuery.initialResultsHandler = ^(HKStatisticsCollectionQuery *q,
360
- HKStatisticsCollection *results,
361
- NSError *error) {
362
- if (error) {
363
- NSLog(@"fetchSteps calories query error: %@", error.localizedDescription);
364
- } else {
365
- [results enumerateStatisticsFromDate:startDate
366
- toDate:endDatePeriod
367
- withBlock:^(HKStatistics *stat, BOOL *stop) {
368
- HKQuantity *quantity = stat.sumQuantity;
369
- int value = quantity ? (int)[quantity doubleValueForUnit:kcalUnit] : 0;
370
- [calorieData addObject:@(value)];
371
- }];
372
- }
373
- dispatch_group_leave(group);
374
- };
375
- [[VisitRnSdkViewManager sharedManager] executeQuery:caloriesQuery];
376
-
377
305
  dispatch_group_notify(group, dispatch_get_main_queue(), ^{
378
- callback(@[stepsData, calorieData]);
306
+ callback(@[stepsData]);
379
307
  });
380
308
  }
381
309
 
382
- -(void) fetchHourlyDistanceWalkingRunning:(NSDate*) endDate callback:(void(^)(NSArray*))callback{
383
- HKQuantityType *distanceType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
384
- NSCalendar *calendar = [NSCalendar currentCalendar];
385
- NSDate *startDate = [[NSCalendar calendarWithIdentifier:NSCalendarIdentifierISO8601] startOfDayForDate:endDate];
386
- HKUnit *distanceUnit = [HKUnit meterUnit];
387
- NSDateComponents *interval = [[NSDateComponents alloc] init];
388
- interval.hour = 1;
389
-
390
- NSDateComponents *dayInteval = [[NSDateComponents alloc] init];
391
- dayInteval.day = 1;
392
- dayInteval.second = -1;
393
- NSDate* endOfDay = [calendar dateByAddingComponents:dayInteval toDate:startDate options:0];
394
-
395
- NSDate *anchorDate = [calendar startOfDayForDate:startDate];
396
- NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endOfDay options:HKQueryOptionStrictStartDate];
397
- NSPredicate *userEnteredValuePredicate = [HKQuery predicateForObjectsWithMetadataKey:HKMetadataKeyWasUserEntered operatorType: NSNotEqualToPredicateOperatorType value: @YES];
398
-
399
- NSCompoundPredicate *compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[predicate, userEnteredValuePredicate]];
400
-
401
- HKStatisticsCollectionQuery *query = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:distanceType quantitySamplePredicate:compoundPredicate options:HKStatisticsOptionCumulativeSum anchorDate:anchorDate intervalComponents:interval];
402
-
403
- query.initialResultsHandler = ^(HKStatisticsCollectionQuery * _Nonnull query, HKStatisticsCollection * _Nullable result, NSError * _Nullable error) {
404
- if (error) {
405
- NSLog(@"*** An error occurred while calculating the statistics: %@ ***",
406
- error.localizedDescription);
407
- return;
408
- }
409
-
410
- NSMutableArray *data = [NSMutableArray arrayWithCapacity:1];
411
- [result enumerateStatisticsFromDate:startDate toDate:endOfDay withBlock:^(HKStatistics * _Nonnull result, BOOL * _Nonnull stop) {
412
- HKQuantity *quantity = result.sumQuantity;
413
- if (quantity) {
414
- int value =(int) [quantity doubleValueForUnit:distanceUnit];
415
- [data addObject:[NSNumber numberWithInt:value]];
416
- } else {
417
- [data addObject:[NSNumber numberWithInt:0]];
418
- }
419
- }];
420
- callback(data);
421
- NSLog(@"fetchDistanceWalkingRunning is,%@",data);
422
- };
423
-
424
- [[VisitRnSdkViewManager sharedManager] executeQuery:query];
425
- }
426
-
427
- -(void) fetchDistanceWalkingRunning:(NSString*) frequency endDate:(NSDate*) endDate days:(NSInteger) days callback:(void(^)(NSArray*))callback{
428
- NSDateComponents *interval = [[NSDateComponents alloc] init];
429
- NSDate *startDate;
430
- interval.day = 1;
431
- NSDate *endDatePeriod;
432
- HKUnit *distanceUnit = [HKUnit meterUnit];
433
- if([frequency isEqualToString:@"day"]){
434
- endDatePeriod = endDate;
435
- startDate = [self->calendar dateByAddingUnit:NSCalendarUnitDay
436
- value:0
437
- toDate:endDatePeriod
438
- options:0];
439
- }else if ([frequency isEqualToString:@"week"]){
440
- NSTimeInterval interval;
441
- [self->calendar rangeOfUnit:NSCalendarUnitWeekOfYear
442
- startDate:&startDate
443
- interval:&interval
444
- forDate:endDate];
445
- endDatePeriod = [startDate dateByAddingTimeInterval:interval-1];
446
- }else if ([frequency isEqualToString:@"month"]){
447
- NSTimeInterval interval;
448
- [self->calendar rangeOfUnit:NSCalendarUnitMonth
449
- startDate:&startDate
450
- interval:&interval
451
- forDate:endDate];
452
- endDatePeriod = [startDate dateByAddingTimeInterval:interval-1];
453
- }else if([frequency isEqualToString:@"custom"]){
454
- endDatePeriod = endDate;
455
- startDate = [self->calendar dateByAddingUnit:NSCalendarUnitDay
456
- value:1-days
457
- toDate:endDatePeriod
458
- options:0];
459
- NSLog(@"startDate and endDate in custom fetchDistanceWalkingRunning is, %@, %@",startDate,endDatePeriod);
460
- }
461
- NSLog(@"startDate and endDate in fetchDistanceWalkingRunning is, %@, %@",startDate,endDatePeriod);
462
- NSDateComponents *anchorComponents = [self->calendar components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear
463
- fromDate:[NSDate date]];
464
- anchorComponents.hour = 0;
465
- NSDate *anchorDate = [self->calendar dateFromComponents:anchorComponents];
466
- HKQuantityType *quantityType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
467
- // Create the query
468
- HKStatisticsCollectionQuery *query = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:quantityType
469
- quantitySamplePredicate:nil
470
- options:HKStatisticsOptionCumulativeSum
471
- anchorDate:anchorDate
472
- intervalComponents:interval];
473
-
474
- // Set the results handler
475
- query.initialResultsHandler = ^(HKStatisticsCollectionQuery *query, HKStatisticsCollection *results, NSError *error) {
476
- if (error) {
477
- // Perform proper error handling here
478
- NSLog(@"*** An error occurred while calculating the statistics: %@ ***",error.localizedDescription);
479
- }
480
- NSMutableArray *data = [NSMutableArray arrayWithCapacity:1];
481
-
482
- [results enumerateStatisticsFromDate:startDate
483
- toDate:endDatePeriod
484
- withBlock:^(HKStatistics *result, BOOL *stop) {
485
-
486
- HKQuantity *quantity = result.sumQuantity;
487
- if (quantity) {
488
- int value = [[NSNumber numberWithInt:[quantity doubleValueForUnit:distanceUnit]] intValue];
489
- NSLog(@"in fetchDistanceWalkingRunning %d", value);
490
-
491
- [data addObject:[NSNumber numberWithInt:value]];
492
- }else{
493
- [data addObject:[NSNumber numberWithInt:0]];
494
- }
495
- }];
496
- callback(data);
497
- };
498
-
499
- [[VisitRnSdkViewManager sharedManager] executeQuery:query];
500
- }
501
-
502
- - (void)fetchSleepCategorySamplesForPredicate:(NSPredicate *)predicate
503
- limit:(NSUInteger)lim
504
- completion:(void (^)(NSArray *, NSError *))completion {
505
-
506
-
507
- NSSortDescriptor *timeSortDescriptor = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierEndDate
508
- ascending:true];
509
-
510
-
511
- // declare the block
512
- void (^handlerBlock)(HKSampleQuery *query, NSArray *results, NSError *error);
513
- // create and assign the block
514
- handlerBlock = ^(HKSampleQuery *query, NSArray *results, NSError *error) {
515
- if (!results) {
516
- if (completion) {
517
- completion(nil, error);
518
- }
519
- return;
520
- }
521
- NSLog(@"the results of sleep is, %@", results);
522
-
523
- if (completion) {
524
- NSMutableArray *data = [NSMutableArray arrayWithCapacity:1];
525
-
526
- dispatch_async(dispatch_get_main_queue(), ^{
527
- for (HKCategorySample *sample in results) {
528
-
529
- NSInteger val = sample.value;
530
-
531
- NSString *valueString;
532
-
533
- switch (val) {
534
- case HKCategoryValueSleepAnalysisInBed:
535
- valueString = @"INBED";
536
- break;
537
- case HKCategoryValueSleepAnalysisAsleep:
538
- valueString = @"ASLEEP";
539
- break;
540
- default:
541
- valueString = @"UNKNOWN";
542
- break;
543
- }
544
-
545
- NSDictionary *elem = @{
546
- @"value" : valueString,
547
- @"startDate" : sample.startDate,
548
- @"endDate" : sample.endDate,
549
- };
550
-
551
- [data addObject:elem];
552
- }
553
-
554
- completion(data, error);
555
- });
556
- }
557
- };
558
-
559
- HKCategoryType *categoryType = [HKObjectType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis];
560
- HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:categoryType
561
- predicate:predicate
562
- limit:lim
563
- sortDescriptors:@[timeSortDescriptor]
564
- resultsHandler:handlerBlock];
565
-
566
- [[VisitRnSdkViewManager sharedManager] executeQuery:query];
567
- }
568
-
569
310
  - (void)requestAuthorization:(void(^)(NSDictionary*))callback {
570
311
 
571
312
  if ([HKHealthStore isHealthDataAvailable] == NO) {
@@ -573,12 +314,7 @@ RCT_REMAP_METHOD(multiply,
573
314
  return;
574
315
  }
575
316
  NSArray *writeTypes = @[[HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount]];
576
- NSArray *readTypes = @[[HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount],
577
- [HKSampleType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis],
578
- [HKSampleType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierBiologicalSex],
579
- [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning],
580
- [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned],
581
- [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierBasalEnergyBurned]];
317
+ NSArray *readTypes = @[[HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount]];
582
318
 
583
319
  [[VisitRnSdkViewManager sharedManager] requestAuthorizationToShareTypes:[NSSet setWithArray:writeTypes] readTypes:[NSSet setWithArray:readTypes]
584
320
  completion:^(BOOL success, NSError *error) {
@@ -597,66 +333,22 @@ RCT_REMAP_METHOD(multiply,
597
333
  }
598
334
 
599
335
  -(void) onHealthKitPermissionGranted:(void(^)(NSDictionary*))callback{
600
- dispatch_group_t loadDetailsGroup=dispatch_group_create();
601
- __block NSString* numberOfSteps = 0;
602
- __block NSTimeInterval totalSleepTime = 0;
603
- NSLog(@"gender is, %@",gender);
604
- for (int i = 0; i<2; i++) {
605
-
606
- dispatch_group_enter(loadDetailsGroup);
607
- if(i==0){
608
- // getting steps for current day
609
- [self fetchSteps:@"day" endDate:[NSDate date] days:0 callback:^(NSArray * result) {
610
- if([[result objectAtIndex:0] count]>0){
611
- numberOfSteps = [[result objectAtIndex:0] objectAtIndex:0];
612
- }
613
- dispatch_group_leave(loadDetailsGroup);
614
- }];
615
- }else if (i==1){
616
- // getting sleep pattern for the day past
617
- [self fetchSleepPattern:[NSDate date] frequency:@"day" days:0 callback:^(NSArray * result) {
618
- NSLog(@"Sleep result is, %@",result);
619
- if([result count]>0){
620
- for (NSDictionary* item in result) {
621
- NSString* sleepValue = [item valueForKey:@"value"];
622
- if([sleepValue isEqualToString:@"INBED"]||[sleepValue isEqualToString:@"ASLEEP"]){
623
- NSDate* startDate = [item valueForKey:@"startDate"];
624
- NSDate* endDate = [item valueForKey:@"endDate"];
625
- NSTimeInterval duration = [endDate timeIntervalSinceDate:startDate] / 60;
626
- totalSleepTime+=duration;
627
- NSLog(@"Sleep value is, %@, while duration is %f",sleepValue,duration);
628
- }
629
- }
630
- }
631
- dispatch_group_leave(loadDetailsGroup);
632
- }];
633
- }
634
- }
635
-
636
- // Now outside the loop wait until everything is done. NOTE: this will
637
- // not block execution, the provided block will be called
638
- // asynchronously at a later point.
639
- dispatch_group_notify(loadDetailsGroup,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^{
640
- self->gender= [self readGender];
641
- if([self->gender isEqualToString:@"Male"]){
642
- self->bmrCaloriesPerHour = 1662 / 24;
643
- }else{
644
- self->bmrCaloriesPerHour = 1493 / 24;
336
+ // getting steps for current day
337
+ [self fetchSteps:@"day" endDate:[NSDate date] days:0 callback:^(NSArray * result) {
338
+ // Must not stay nil: an NSDictionary literal throws on a nil value.
339
+ id numberOfSteps = @0;
340
+ if([result count]>0 && [[result objectAtIndex:0] count]>0){
341
+ numberOfSteps = [[result objectAtIndex:0] objectAtIndex:0];
645
342
  }
646
343
  NSLog(@"the steps result is, %@",numberOfSteps);
647
- NSLog(@"total sleep time is %f",totalSleepTime);
648
- // if(!self->hasLoadedOnce){
649
- NSDictionary *element = @{
650
- @"numberOfSteps" : numberOfSteps,
651
- @"sleepTime" : [NSNumber numberWithInt:totalSleepTime]
652
- };
653
- // NSString *javascript = [NSString stringWithFormat:@"updateFitnessPermissions(true,'%@','%ld')",numberOfSteps, sleepTime];
654
- dispatch_async(dispatch_get_main_queue(), ^{
655
- self->hasLoadedOnce = true;
656
- callback(element);
657
- });
658
- // }
659
- });
344
+ NSDictionary *element = @{
345
+ @"numberOfSteps" : numberOfSteps,
346
+ };
347
+ dispatch_async(dispatch_get_main_queue(), ^{
348
+ self->hasLoadedOnce = true;
349
+ callback(element);
350
+ });
351
+ }];
660
352
  }
661
353
 
662
354
  -(void) canAccessHealthKit: (void(^)(BOOL))callback {
@@ -685,77 +377,6 @@ RCT_REMAP_METHOD(multiply,
685
377
  }];
686
378
  }
687
379
 
688
- -(void) fetchSleepPattern:(NSDate *) endDate frequency:(NSString*) frequency days:(NSInteger) days callback:(void(^)(NSArray*))callback{
689
- NSDate *startDate;
690
- NSDate *endDatePeriod;
691
- if([frequency isEqualToString:@"day"]){
692
- NSTimeInterval interval;
693
- NSLog(@"startDate and endDate in fetchSleepPattern before is, %@ %@",startDate,endDatePeriod);
694
- [self->calendar rangeOfUnit:NSCalendarUnitDay
695
- startDate:&startDate
696
- interval:&interval
697
- forDate:endDate];
698
- endDatePeriod = [startDate dateByAddingTimeInterval:interval-1];
699
- startDate = [startDate dateByAddingTimeInterval:-3600*2];
700
- NSLog(@"startDate and endDate in fetchSleepPattern is, %@ %@",startDate,endDatePeriod);
701
- }else if ([frequency isEqualToString:@"week"]){
702
- NSTimeInterval interval;
703
- [self->calendar rangeOfUnit:NSCalendarUnitWeekOfYear
704
- startDate:&startDate
705
- interval:&interval
706
- forDate:endDate];
707
- endDatePeriod = [startDate dateByAddingTimeInterval:interval-1];
708
- }else if([frequency isEqualToString:@"custom"]){
709
- endDatePeriod = endDate;
710
- startDate = [self->calendar dateByAddingUnit:NSCalendarUnitDay
711
- value:-days
712
- toDate:endDatePeriod
713
- options:0];
714
- // NSLog(@"startDate and endDate in custom fetchSleepPattern is, %@, %@",startDate,endDatePeriod);
715
- }
716
- // NSLog(@"startDate and endDate in fetchSleepPattern is, %@ %@",startDate,endDatePeriod);
717
- NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDatePeriod options:HKQueryOptionStrictStartDate];
718
- [self fetchSleepCategorySamplesForPredicate:predicate
719
- limit:HKObjectQueryNoLimit
720
- completion:^(NSArray *results, NSError *error) {
721
- if(results){
722
- // NSLog(@"fetchSleepCategorySamplesForPredicate result, %@",results);
723
- callback(results);
724
- return;
725
- } else {
726
- // NSLog(@"error getting sleep samples: %@", error);
727
- return;
728
- }
729
- }];
730
- }
731
-
732
- -(NSMutableArray*) getBlankSleepWeeks:(NSUInteger) currentCount date:(NSDate*) date{
733
- NSMutableArray *result = [[NSMutableArray alloc]init];
734
- NSInteger value = 1;
735
- NSDate *nextDayTime=date;
736
- NSNumber *nextDayTimeStamp;
737
- NSDateComponents *dateComponents;
738
- NSString* day;
739
- NSLog(@"day is, %@",day);
740
- int counter =(int) currentCount;
741
- while(counter<7){
742
- nextDayTime = [self->calendar dateByAddingUnit:NSCalendarUnitDay value:value toDate:nextDayTime options:NSCalendarMatchStrictly];
743
- nextDayTimeStamp = [NSNumber numberWithDouble: [@(floor([nextDayTime timeIntervalSince1970] * 1000)) longLongValue]];
744
- dateComponents = [self->calendar components: NSCalendarUnitWeekday fromDate: nextDayTime];
745
- day = self->calendar.shortWeekdaySymbols[dateComponents.weekday-1];
746
- NSDictionary *element = @{
747
- @"sleepTime" : @0,
748
- @"wakeupTime" : @0,
749
- @"day" : day,
750
- @"startTimestamp" : nextDayTimeStamp,
751
- };
752
- NSLog(@"element is %@",element);
753
- [result addObject:[NSMutableDictionary dictionaryWithDictionary:element]];
754
- counter++;
755
- }
756
- return result;
757
- }
758
-
759
380
  -(void) evaluateJavascript:(NSArray *) data type:(NSString *) type frequency:(NSString *) frequency activityTime:(NSString *) activityTime callback:(void(^)(NSArray*))callback{
760
381
  NSString* hoursInDay = @"[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]";
761
382
  NSString* daysInWeek = @"[1,2,3,4,5,6,7]";
@@ -769,15 +390,7 @@ RCT_REMAP_METHOD(multiply,
769
390
  }else if ([frequency isEqualToString:@"month"]){
770
391
  samples=daysInMonth;
771
392
  }
772
- if([type isEqualToString:@"steps"] || [type isEqualToString:@"calories"]){
773
- if([type isEqualToString:@"steps"]){
774
- jsonArrayData = [[data objectAtIndex:0] componentsJoinedByString:@","];
775
- }else{
776
- jsonArrayData = [[data objectAtIndex:1] componentsJoinedByString:@","];
777
- }
778
- }else{
779
- jsonArrayData = [data componentsJoinedByString:@","];
780
- }
393
+ jsonArrayData = [[data objectAtIndex:0] componentsJoinedByString:@","];
781
394
  NSString *javascript = [NSString stringWithFormat:@"DetailedGraph.updateData(%@,[%@],'%@','%@','%@')", samples, jsonArrayData, type,frequency, activityTime];
782
395
  dispatch_async(dispatch_get_main_queue(), ^{
783
396
  callback(@[javascript]);
@@ -785,148 +398,40 @@ RCT_REMAP_METHOD(multiply,
785
398
  }
786
399
 
787
400
  -(void) renderGraphData:(NSString *) type frequency:(NSString *) frequency date:(NSDate *) date callback:(void(^)(NSArray*))callback{
788
- if([type isEqualToString:@"steps"] || [type isEqualToString:@"distance"]||[type isEqualToString:@"calories"]){
789
- dispatch_group_t loadDetailsGroup=dispatch_group_create();
790
- __block NSArray* stepsOrDistance = 0;
791
- __block NSString* totalActivityDuration = 0;
792
- for (int i = 0; i<2; i++) {
793
- dispatch_group_enter(loadDetailsGroup);
794
- if(i==0){
795
- [self getActivityTime:date frequency:frequency days:0 callback:^(NSMutableArray * result){
796
- totalActivityDuration = [result objectAtIndex:0];
401
+ if(![type isEqualToString:@"steps"]){
402
+ NSLog(@"renderGraphData ignoring unsupported type: %@",type);
403
+ callback(@[]);
404
+ return;
405
+ }
406
+ dispatch_group_t loadDetailsGroup=dispatch_group_create();
407
+ __block NSArray* stepsData = 0;
408
+ __block NSString* totalActivityDuration = 0;
409
+ for (int i = 0; i<2; i++) {
410
+ dispatch_group_enter(loadDetailsGroup);
411
+ if(i==0){
412
+ [self getActivityTime:date frequency:frequency days:0 callback:^(NSMutableArray * result){
413
+ totalActivityDuration = [result objectAtIndex:0];
414
+ dispatch_group_leave(loadDetailsGroup);
415
+ }];
416
+ }else if(i==1){
417
+ if([frequency isEqualToString:@"day"]){
418
+ [self fetchHourlySteps:date callback:^(NSArray * result) {
419
+ stepsData = result;
797
420
  dispatch_group_leave(loadDetailsGroup);
798
421
  }];
799
- }else if(i==1){
800
- if([type isEqualToString:@"steps"] || [type isEqualToString:@"calories"]){
801
- if([frequency isEqualToString:@"day"]){
802
- [self fetchHourlySteps:date callback:^(NSArray * result) {
803
- stepsOrDistance = result;
804
- dispatch_group_leave(loadDetailsGroup);
805
- }];
806
- }else{
807
- [self fetchSteps:frequency endDate: date days:0 callback:^(NSArray * result) {
808
- stepsOrDistance = result;
809
- dispatch_group_leave(loadDetailsGroup);
810
- }];
811
- }
812
- }else if ([type isEqualToString:@"distance"]){
813
- if([frequency isEqualToString:@"day"]){
814
- [self fetchHourlyDistanceWalkingRunning:date callback:^(NSArray * result) {
815
- stepsOrDistance = result;
816
- dispatch_group_leave(loadDetailsGroup);
817
- }];
818
- }else{
819
- [self fetchDistanceWalkingRunning:frequency endDate: date days:0 callback:^(NSArray * result) {
820
- stepsOrDistance = result;
821
- dispatch_group_leave(loadDetailsGroup);
822
- }];
823
- }
824
- }
825
- }
826
- }
827
- dispatch_group_notify(loadDetailsGroup,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^{
828
- [self evaluateJavascript:stepsOrDistance type:type frequency:frequency activityTime:totalActivityDuration callback:^(NSArray * data) {
829
- callback(data);
830
- }];
831
- });
832
- }else if([type isEqualToString:@"sleep"]){
833
- if([frequency isEqualToString:@"day"]){
834
- [self fetchSleepPattern:date frequency:frequency days:0 callback:^(NSArray * results) {
835
- NSNumber* sleepTime = 0;
836
- NSNumber* wakeTime = 0;
837
- int count = 0;
838
- for (NSDictionary *object in results) {
839
- NSString* sleepValue = [object valueForKey:@"value"];
840
- if([sleepValue isEqualToString:@"INBED"]||[sleepValue isEqualToString:@"ASLEEP"]){
841
- if(count==0){
842
- sleepTime =
843
- [NSNumber numberWithDouble: [@(floor([[object valueForKey:@"startDate"] timeIntervalSince1970] * 1000)) longLongValue]];
844
-
845
- }
846
- wakeTime =
847
- [NSNumber numberWithDouble: [@(floor([[object valueForKey:@"endDate"] timeIntervalSince1970] * 1000)) longLongValue]];
848
- count++;
849
- }
850
- }
851
- NSLog(@"sleepTime and wakeTime data, %@ %@",sleepTime, wakeTime);
852
-
853
- if(sleepTime && wakeTime){
854
- NSString *javascript = [NSString stringWithFormat:@"DetailedGraph.updateDailySleep(%@,%@)", sleepTime,wakeTime];
855
- callback(@[javascript]);
856
- }else{
857
- NSString *javascript = [NSString stringWithFormat:@"DetailedGraph.updateDailySleep(0,0)"];
858
- callback(@[javascript]);
859
- }
860
- } ];
861
422
  }else{
862
- [self fetchSleepPattern:date frequency:frequency days:0 callback:^(NSArray * results) {
863
- NSMutableArray *data = [[NSMutableArray alloc]init];
864
- NSLog(@"weekly sleep results, %@", results);
865
- if([results count]){
866
- for (NSDictionary* item in results) {
867
- NSString* sleepValue = [item valueForKey:@"value"];
868
- if([sleepValue isEqualToString:@"INBED"]||[sleepValue isEqualToString:@"ASLEEP"]){
869
- NSDate* startDate = [item valueForKey:@"startDate"];
870
- NSDate* endDate = [item valueForKey:@"endDate"];
871
- NSTimeInterval interval;
872
- NSNumber* sleepTime =
873
- [NSNumber numberWithDouble: [@(floor([startDate timeIntervalSince1970] * 1000)) longLongValue]];
874
- NSNumber* wakeupTime =
875
- [NSNumber numberWithDouble: [@(floor([endDate timeIntervalSince1970] * 1000)) longLongValue]];
876
- NSLog(@"startDate before calendar function ,%@",startDate);
877
- [self->calendar rangeOfUnit:NSCalendarUnitDay
878
- startDate:&startDate
879
- interval:&interval
880
- forDate:endDate];
881
- NSLog(@"startDate after calendar function ,%@",startDate);
882
- NSNumber* startTimestamp =
883
- [NSNumber numberWithDouble: [@(floor([startDate timeIntervalSince1970] * 1000)) longLongValue]];
884
- NSDateComponents * dateComponents = [self->calendar components: NSCalendarUnitDay | NSCalendarUnitWeekday fromDate: endDate];
885
- NSString* day =self->calendar.shortWeekdaySymbols[dateComponents.weekday - 1];
886
- NSLog(@"Day name: %@", day);
887
- NSDictionary *element = @{
888
- @"sleepTime" : sleepTime,
889
- @"wakeupTime" : wakeupTime,
890
- @"day" : day,
891
- @"startTimestamp" : startTimestamp,
892
- };
893
- NSMutableDictionary *elem = [NSMutableDictionary dictionaryWithDictionary:element];
894
-
895
- NSLog(@"data is, ====>> %@",data);
896
- if([data count]>0){
897
- for (int i=0;i<[data count]; i++) {
898
- NSMutableDictionary* item = [data objectAtIndex:i];
899
- NSString* itemDay = [item objectForKey:@"day"];
900
- NSString* itemSleepTime = [item objectForKey:@"sleepTime"];
901
- if([itemDay isEqualToString:day]){
902
- [elem setValue:itemSleepTime forKey:@"sleepTime"];
903
- [data removeObjectAtIndex:i];
904
- NSLog(@"removed day is, ====>> %@",itemDay);
905
- }
906
- }
907
- [data addObject:elem];
908
- }else{
909
- [data addObject:elem];
910
- }
911
- }
912
- }
913
- }
914
- if([data count]<7 && [data count]>0){
915
- NSMutableDictionary* item = [data objectAtIndex:[data count]-1];
916
- NSNumber* startTimeStamp = [item objectForKey:@"startTimestamp"];
917
- NSTimeInterval unixTimeStamp = [startTimeStamp doubleValue] / 1000.0;
918
- NSMutableArray* newData = [self getBlankSleepWeeks:[data count] date:[NSDate dateWithTimeIntervalSince1970:unixTimeStamp]];
919
- [data addObjectsFromArray:newData];
920
- }
921
- NSLog(@"data is, %@",data);
922
- NSData* jsonArray = [NSJSONSerialization dataWithJSONObject:data options:NSJSONWritingPrettyPrinted error:nil ];
923
- NSString *jsonString = [[NSString alloc] initWithData:jsonArray encoding:NSUTF8StringEncoding];
924
- NSString *javascript = [NSString stringWithFormat:@"DetailedGraph.updateSleepData(JSON.stringify(%@))", jsonString];
925
- callback(@[javascript]);
423
+ [self fetchSteps:frequency endDate: date days:0 callback:^(NSArray * result) {
424
+ stepsData = result;
425
+ dispatch_group_leave(loadDetailsGroup);
926
426
  }];
927
- }
928
-
427
+ }
428
+ }
929
429
  }
430
+ dispatch_group_notify(loadDetailsGroup,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^{
431
+ [self evaluateJavascript:stepsData type:type frequency:frequency activityTime:totalActivityDuration callback:^(NSArray * data) {
432
+ callback(data);
433
+ }];
434
+ });
930
435
  }
931
436
 
932
437
  - (NSDate *)convertStringToDate:(NSString *)date {
@@ -977,15 +482,13 @@ RCT_REMAP_METHOD(multiply,
977
482
  });
978
483
  }
979
484
 
980
- -(void) preprocessEmbellishRequest:(NSArray*) steps calories:(NSArray*) calories distance:(NSArray*) distance date:(NSDate*) date callback:(void(^)(NSArray*))callback{
981
- NSLog(@"steps=%@, calories=%@, distance=%@, date=%@",steps, calories, distance, date);
485
+ -(void) preprocessEmbellishRequest:(NSArray*) steps date:(NSDate*) date callback:(void(^)(NSArray*))callback{
486
+ NSLog(@"steps=%@, date=%@",steps, date);
982
487
  NSMutableArray* embellishData = [NSMutableArray new];
983
488
  int count=0;
984
489
  for (NSNumber* step in steps) {
985
490
  NSDictionary *dict = @{
986
491
  @"st" : step,
987
- @"c" : [calories objectAtIndex:count],
988
- @"d" : [distance objectAtIndex:count],
989
492
  @"h" : [NSNumber numberWithInt:count],
990
493
  @"s" : @"",
991
494
  };
@@ -1002,166 +505,77 @@ RCT_REMAP_METHOD(multiply,
1002
505
  callback(@[httpBody]);
1003
506
  }
1004
507
 
508
+ // Daily sync payload. Steps-only: `steps` comes from HKQuantityTypeIdentifierStepCount
509
+ // and `activity` is the active-minutes total derived from the same step samples.
1005
510
  -(void)callSyncData:(NSInteger) days dates:(NSMutableArray*)dates callback:(void(^)(NSArray*))callback{
1006
511
  dispatch_group_t syncDataGroup=dispatch_group_create();
1007
512
  __block NSArray* steps;
1008
- __block NSArray* calorie;
1009
- __block NSArray* distanceData;
1010
513
  __block NSArray* activityData;
1011
- __block NSArray* sleep;
1012
- // NSLog(@"days are %ld",(long)days);
1013
- for (int i = 0; i<4; i++) {
514
+ for (int i = 0; i<2; i++) {
1014
515
  dispatch_group_enter(syncDataGroup);
1015
516
  if(i==0){
1016
517
  [self fetchSteps:@"custom" endDate:[NSDate date] days:days callback:^(NSArray * data) {
1017
518
  NSLog(@"steps data for custom range is, %@ length %lu",[data objectAtIndex:0],[[data objectAtIndex:0] count]);
1018
519
  steps = [data objectAtIndex:0];
1019
- calorie = [data objectAtIndex:1];
1020
520
  dispatch_group_leave(syncDataGroup);
1021
521
  }];
1022
522
  }else if(i==1){
1023
- [self fetchDistanceWalkingRunning:@"custom" endDate:[NSDate date] days:days callback:^(NSArray * distance) {
1024
- NSLog(@"distance data for custom range is, %@ length %lu",distance, [distance count]);
1025
- distanceData=distance;
1026
- dispatch_group_leave(syncDataGroup);
1027
- }];
1028
- }else if(i==2){
1029
523
  [self getActivityTime:[NSDate date] frequency:@"custom" days:days callback:^(NSMutableArray * activity) {
1030
524
  NSMutableArray* arr = [activity objectAtIndex:1];
1031
525
  NSLog(@"activity data for custom range is, %@ length %lu",activity, [arr count]);
1032
526
  activityData = arr;
1033
527
  dispatch_group_leave(syncDataGroup);
1034
528
  }];
1035
- }else if(i==3){
1036
- [self fetchSleepPattern:[NSDate date] frequency:@"custom" days:days callback:^(NSArray * sleepData) {
1037
- NSMutableArray *data = [[NSMutableArray alloc]init];
1038
- for (NSDictionary* item in sleepData) {
1039
- NSString* sleepValue = [item valueForKey:@"value"];
1040
- if([sleepValue isEqualToString:@"INBED"]||[sleepValue isEqualToString:@"ASLEEP"]){
1041
- NSDate* startDate = [item valueForKey:@"startDate"];
1042
- NSDate* endDate = [item valueForKey:@"endDate"];
1043
- NSTimeInterval interval;
1044
- NSNumber* sleepTime =
1045
- [NSNumber numberWithDouble: [@(floor([startDate timeIntervalSince1970] * 1000)) longLongValue]];
1046
- NSNumber* wakeupTime =
1047
- [NSNumber numberWithDouble: [@(floor([endDate timeIntervalSince1970] * 1000)) longLongValue]];
1048
- // NSLog(@"startDate before calendar function ,%@",startDate);
1049
- [self->calendar rangeOfUnit:NSCalendarUnitDay
1050
- startDate:&startDate
1051
- interval:&interval
1052
- forDate:endDate];
1053
- // NSLog(@"startDate after calendar function ,%@",startDate);
1054
- NSNumber* startTimestamp =
1055
- [NSNumber numberWithDouble: [@(floor([startDate timeIntervalSince1970] * 1000)) longLongValue]];
1056
- NSDictionary *element = @{
1057
- @"sleepTime" : sleepTime,
1058
- @"wakeupTime" : wakeupTime,
1059
- @"endDate" : endDate,
1060
- @"startTimestamp" : startTimestamp,
1061
- };
1062
- NSMutableDictionary *elem = [NSMutableDictionary dictionaryWithDictionary:element];
1063
-
1064
- if([data count]>0){
1065
- for (int i=0;i<[data count]; i++) {
1066
- NSMutableDictionary* item = [data objectAtIndex:i];
1067
- NSDate* itemEndDate = [item objectForKey:@"endDate"];
1068
- NSString* itemSleepTime = [item objectForKey:@"sleepTime"];
1069
- if([[NSCalendar currentCalendar] isDate:itemEndDate inSameDayAsDate:endDate]){
1070
- [elem setValue:itemSleepTime forKey:@"sleepTime"];
1071
- [data removeObjectAtIndex:i];
1072
- // NSLog(@"removed date is, ====>> %@",endDate);
1073
- }
1074
- }
1075
- [data addObject:elem];
1076
- }else{
1077
- [data addObject:elem];
1078
- }
1079
- }
1080
- }
1081
- sleep = data;
1082
- NSLog(@"fetchSleepPattern data is, ====>> %lu %@",(unsigned long)[data count],data);
1083
- dispatch_group_leave(syncDataGroup);
1084
- }];
1085
529
  }
1086
530
  }
1087
- // NSLog(@"callSyncData steps=%@, calories=%@, distance=%@, activity=%@, sleep=%@",steps, calorie, distanceData, activityData, sleep);
1088
531
 
1089
532
  dispatch_group_notify(syncDataGroup,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^{
1090
- if([steps count]>0 && [distanceData count]>0 && [activityData count]>0 && [sleep count]>0)
1091
- {
1092
- NSMutableArray* dailySyncData =[NSMutableArray new];
1093
- int count = 0;
1094
- for (NSDate* date in dates) {
1095
- NSDictionary* dict = @{
1096
- @"steps":[steps objectAtIndex:count],
1097
- @"calories":[calorie objectAtIndex:count],
1098
- @"distance":[distanceData objectAtIndex:count],
1099
- @"date":date
1100
- };
1101
- [dailySyncData addObject:[NSMutableDictionary dictionaryWithDictionary:dict]];
1102
- count++;
1103
- }
1104
- for (NSMutableDictionary* dict in dailySyncData) {
1105
- for(NSMutableDictionary* sleepData in sleep){
1106
- if([[NSCalendar currentCalendar] isDate:[sleepData objectForKey:@"endDate"] inSameDayAsDate:[dict objectForKey:@"date"]]){
1107
- NSString* sleepTime = [sleepData objectForKey:@"sleepTime"];
1108
- NSString* wakeupTime = [sleepData objectForKey:@"wakeupTime"];
1109
- [dict setObject:[NSString stringWithFormat:@"%@-%@",sleepTime,wakeupTime] forKey:@"sleep"];
1110
- }
533
+ if([steps count]>0 && [activityData count]>0)
534
+ {
535
+ NSMutableArray* dailySyncData =[NSMutableArray new];
536
+ int count = 0;
537
+ for (NSDate* date in dates) {
538
+ NSDictionary* dict = @{
539
+ @"steps":[steps objectAtIndex:count],
540
+ @"date":date
541
+ };
542
+ [dailySyncData addObject:[NSMutableDictionary dictionaryWithDictionary:dict]];
543
+ count++;
1111
544
  }
1112
-
1113
- for(NSMutableDictionary* activity in activityData){
1114
- if([[NSCalendar currentCalendar] isDate:[activity objectForKey:@"date"] inSameDayAsDate:[dict objectForKey:@"date"]]){
1115
- NSString* activityValue = [activity objectForKey:@"value"];
1116
- [dict setObject:activityValue forKey:@"activity"];
545
+ for (NSMutableDictionary* dict in dailySyncData) {
546
+ for(NSMutableDictionary* activity in activityData){
547
+ if([[NSCalendar currentCalendar] isDate:[activity objectForKey:@"date"] inSameDayAsDate:[dict objectForKey:@"date"]]){
548
+ NSString* activityValue = [activity objectForKey:@"value"];
549
+ [dict setObject:activityValue forKey:@"activity"];
550
+ }
1117
551
  }
552
+
553
+ [dict setObject: [NSNumber numberWithDouble: [@(floor([[dict objectForKey:@"date"] timeIntervalSince1970] * 1000)) longLongValue]]
554
+ forKey:@"date"];
1118
555
  }
1119
-
1120
- [dict setObject: [NSNumber numberWithDouble: [@(floor([[dict objectForKey:@"date"] timeIntervalSince1970] * 1000)) longLongValue]]
1121
- forKey:@"date"];
556
+ NSDictionary *httpBody = @{
557
+ @"fitnessData" : dailySyncData,
558
+ };
559
+ callback(@[httpBody]);
560
+ } else {
561
+ // Callback must always fire so callers can proceed even when a
562
+ // sub-fetch (steps/activity) returned no data.
563
+ callback(@[]);
1122
564
  }
1123
- NSDictionary *httpBody = @{
1124
- @"fitnessData" : dailySyncData,
1125
- };
1126
- callback(@[httpBody]);
1127
-
1128
- } else {
1129
- // Callback must always fire so callers can proceed even when a
1130
- // sub-fetch (steps/distance/activity/sleep) returned no data.
1131
- callback(@[]);
1132
- }
1133
565
  });
1134
566
  }
1135
567
 
1136
568
  -(void)callEmbellishApi:(NSMutableArray*) dates callback:(void(^)(NSArray*))callback{
1137
569
  for (NSDate* date in dates) {
1138
- dispatch_group_t loadDetailsGroup=dispatch_group_create();
1139
- __block NSArray* steps;
1140
- __block NSArray* calories;
1141
- __block NSArray* distance;
1142
- for(int i = 0; i<2;i++){
1143
- dispatch_group_enter(loadDetailsGroup);
1144
- if(i==0){
1145
- [self fetchHourlySteps:date callback:^(NSArray * data) {
1146
- steps = [data objectAtIndex:0];
1147
- calories = [data objectAtIndex:1];
1148
- dispatch_group_leave(loadDetailsGroup);
1149
- }];
1150
- }else if(i==1){
1151
- [self fetchHourlyDistanceWalkingRunning:date callback:^(NSArray * dist) {
1152
- distance = dist;
1153
- dispatch_group_leave(loadDetailsGroup);
1154
- }];
1155
- }
1156
- }
1157
- dispatch_group_notify(loadDetailsGroup,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^{
1158
- if([steps count]>0 && [calories count] > 0 && [distance count]>0){
1159
- [self preprocessEmbellishRequest:steps calories:calories distance:distance date:date callback:^(NSArray * data) {
1160
- NSLog(@"preprocessEmbellishRequest data, %@",data);
1161
- callback(data);
570
+ [self fetchHourlySteps:date callback:^(NSArray * data) {
571
+ NSArray* steps = [data count] > 0 ? [data objectAtIndex:0] : @[];
572
+ if([steps count]>0){
573
+ [self preprocessEmbellishRequest:steps date:date callback:^(NSArray * result) {
574
+ NSLog(@"preprocessEmbellishRequest data, %@",result);
575
+ callback(result);
1162
576
  }];
1163
577
  }
1164
- });
578
+ }];
1165
579
  }
1166
580
  }
1167
581
 
@@ -1190,11 +604,6 @@ RCT_EXPORT_METHOD(connectToAppleHealth:(RCTResponseSenderBlock)callback)
1190
604
  [NSSet setWithObject:[HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount]];
1191
605
  NSSet *readTypes = [NSSet setWithArray:@[
1192
606
  [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount],
1193
- [HKObjectType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis],
1194
- [HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierBiologicalSex],
1195
- [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning],
1196
- [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned],
1197
- [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBasalEnergyBurned],
1198
607
  ]];
1199
608
 
1200
609
  __weak typeof(self) weakSelf = self;
@@ -1321,9 +730,9 @@ RCT_EXPORT_METHOD(renderGraph:(NSDictionary *)input callback:(RCTResponseSenderB
1321
730
  [task resume];
1322
731
  }
1323
732
 
1324
- // Fans out to fetchHourlySteps + fetchHourlyDistanceWalkingRunning per date,
1325
- // then preprocessEmbellishRequest, collecting all httpBody dicts. Always fires
1326
- // completion exactly once, even when no batches are produced.
733
+ // Fans out to fetchHourlySteps per date, then preprocessEmbellishRequest,
734
+ // collecting all httpBody dicts. Always fires completion exactly once, even
735
+ // when no batches are produced.
1327
736
  - (void)collectEmbellishBatchesForDates:(NSArray<NSDate *> *)dates
1328
737
  completion:(void (^)(NSArray<NSDictionary *> *batches))completion
1329
738
  {
@@ -1339,32 +748,21 @@ RCT_EXPORT_METHOD(renderGraph:(NSDictionary *)input callback:(RCTResponseSenderB
1339
748
  for (NSDate *date in dates) {
1340
749
  dispatch_group_enter(outer);
1341
750
  __block NSArray *steps = @[];
1342
- __block NSArray *calories = @[];
1343
- __block NSArray *distance = @[];
1344
751
  dispatch_group_t inner = dispatch_group_create();
1345
752
 
1346
753
  dispatch_group_enter(inner);
1347
754
  [weakSelf fetchHourlySteps:date callback:^(NSArray *data) {
1348
- if (data.count >= 2) {
755
+ if (data.count >= 1) {
1349
756
  steps = data[0] ?: @[];
1350
- calories = data[1] ?: @[];
1351
757
  }
1352
758
  dispatch_group_leave(inner);
1353
759
  }];
1354
760
 
1355
- dispatch_group_enter(inner);
1356
- [weakSelf fetchHourlyDistanceWalkingRunning:date callback:^(NSArray *dist) {
1357
- distance = dist ?: @[];
1358
- dispatch_group_leave(inner);
1359
- }];
1360
-
1361
761
  dispatch_group_notify(inner,
1362
762
  dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
1363
763
  __strong typeof(weakSelf) strongSelf = weakSelf;
1364
- if (steps.count > 0 && calories.count > 0 && distance.count > 0 && strongSelf) {
764
+ if (steps.count > 0 && strongSelf) {
1365
765
  [strongSelf preprocessEmbellishRequest:steps
1366
- calories:calories
1367
- distance:distance
1368
766
  date:date
1369
767
  callback:^(NSArray *data) {
1370
768
  if (data.count > 0 && [data[0] isKindOfClass:[NSDictionary class]]) {
@@ -1569,33 +967,15 @@ RCT_EXPORT_METHOD(fetchHourlyData:(NSInteger)gfHourlyLastSync resolver:(RCTPromi
1569
967
  NSDate* hourlyDataSyncTime = [NSDate dateWithTimeIntervalSince1970:gfHourlyLastSync/1000];
1570
968
  [self canAccessHealthKit:^(BOOL value){
1571
969
  if(value){
1572
- dispatch_group_t loadDetailsGroup=dispatch_group_create();
1573
- __block NSArray* steps;
1574
- __block NSArray* calories;
1575
- __block NSArray* distance;
1576
- for(int i = 0; i<2;i++){
1577
- dispatch_group_enter(loadDetailsGroup);
1578
- if(i==0){
1579
- [self fetchHourlySteps:hourlyDataSyncTime callback:^(NSArray * data) {
1580
- steps = [data objectAtIndex:0];
1581
- calories = [data objectAtIndex:1];
1582
- dispatch_group_leave(loadDetailsGroup);
1583
- }];
1584
- }else if(i==1){
1585
- [self fetchHourlyDistanceWalkingRunning:hourlyDataSyncTime callback:^(NSArray * dist) {
1586
- distance = dist;
1587
- dispatch_group_leave(loadDetailsGroup);
1588
- }];
1589
- }
1590
- }
1591
- dispatch_group_notify(loadDetailsGroup,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^{
1592
- if([steps count]>0 && [calories count] > 0 && [distance count]>0){
1593
- [self preprocessEmbellishRequest:steps calories:calories distance:distance date:hourlyDataSyncTime callback:^(NSArray * data) {
1594
- NSLog(@"fetchHourlyData data, %@",data);
1595
- resolve(data);
970
+ [self fetchHourlySteps:hourlyDataSyncTime callback:^(NSArray * data) {
971
+ NSArray* steps = [data count] > 0 ? [data objectAtIndex:0] : @[];
972
+ if([steps count]>0){
973
+ [self preprocessEmbellishRequest:steps date:hourlyDataSyncTime callback:^(NSArray * result) {
974
+ NSLog(@"fetchHourlyData data, %@",result);
975
+ resolve(result);
1596
976
  }];
1597
977
  }
1598
- });
978
+ }];
1599
979
  }else{
1600
980
  NSError* error;
1601
981
  reject(@"error", @"Error fetching hourly data", error);
@@ -1700,11 +1080,6 @@ RCT_REMAP_METHOD(requestHealthKitAuthorization,
1700
1080
  [NSSet setWithObject:[HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount]];
1701
1081
  NSMutableSet *readTypes = [NSMutableSet setWithArray:@[
1702
1082
  [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount],
1703
- [HKObjectType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis],
1704
- [HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierBiologicalSex],
1705
- [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning],
1706
- [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned],
1707
- [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBasalEnergyBurned],
1708
1083
  ]];
1709
1084
 
1710
1085
  [[VisitRnSdkViewManager sharedManager]
@@ -1783,118 +1158,6 @@ RCT_REMAP_METHOD(getTodayStepCount,
1783
1158
  [[VisitRnSdkViewManager sharedManager] executeQuery:query];
1784
1159
  }
1785
1160
 
1786
- RCT_REMAP_METHOD(getTodaySleepMinutes,
1787
- getTodaySleepMinutesWithResolver:(RCTPromiseResolveBlock)resolve
1788
- rejecter:(RCTPromiseRejectBlock)reject)
1789
- {
1790
- if (![HKHealthStore isHealthDataAvailable]) {
1791
- reject(@"HEALTH_DATA_UNAVAILABLE", @"HealthKit is not available on this device", nil);
1792
- return;
1793
- }
1794
-
1795
- // Sum sleep sessions whose end date falls on today. Look 36 hours back so
1796
- // overnight sessions (e.g., 11pm → 7am) that started yesterday are still
1797
- // considered, matching Apple Health's "sleep on wake day" convention.
1798
- NSCalendar *cal = [NSCalendar currentCalendar];
1799
- NSDate *now = [NSDate date];
1800
- NSDate *startOfDay = [cal startOfDayForDate:now];
1801
- NSDate *lookbackStart = [now dateByAddingTimeInterval:-36 * 60 * 60];
1802
-
1803
- NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:lookbackStart
1804
- endDate:now
1805
- options:HKQueryOptionNone];
1806
- HKCategoryType *sleepType = [HKObjectType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis];
1807
- NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierEndDate ascending:YES];
1808
-
1809
- HKSampleQuery *query = [[HKSampleQuery alloc]
1810
- initWithSampleType:sleepType
1811
- predicate:predicate
1812
- limit:HKObjectQueryNoLimit
1813
- sortDescriptors:@[sort]
1814
- resultsHandler:^(HKSampleQuery *q, NSArray<__kindof HKSample *> *results, NSError *error) {
1815
- if (error) {
1816
- reject(@"SLEEP_QUERY_FAILED", error.localizedDescription ?: @"Failed to query sleep data", error);
1817
- return;
1818
- }
1819
-
1820
- NSTimeInterval totalSleepSeconds = 0;
1821
- for (HKCategorySample *sample in results) {
1822
- if (![self isAsleepSleepAnalysisValue:sample.value]) {
1823
- continue;
1824
- }
1825
- // Only count samples that ended today.
1826
- if ([sample.endDate compare:startOfDay] == NSOrderedAscending) {
1827
- continue;
1828
- }
1829
- totalSleepSeconds += [sample.endDate timeIntervalSinceDate:sample.startDate];
1830
- }
1831
- NSInteger minutes = (NSInteger)(totalSleepSeconds / 60.0);
1832
- resolve(@(minutes));
1833
- }];
1834
-
1835
- [[VisitRnSdkViewManager sharedManager] executeQuery:query];
1836
- }
1837
-
1838
- - (BOOL)isAsleepSleepAnalysisValue:(NSInteger)value
1839
- {
1840
- if (value == HKCategoryValueSleepAnalysisInBed) {
1841
- return YES;
1842
- }
1843
- if (@available(iOS 16.0, *)) {
1844
- if (value == HKCategoryValueSleepAnalysisAsleepUnspecified ||
1845
- value == HKCategoryValueSleepAnalysisAsleepCore ||
1846
- value == HKCategoryValueSleepAnalysisAsleepDeep ||
1847
- value == HKCategoryValueSleepAnalysisAsleepREM) {
1848
- return YES;
1849
- }
1850
- }
1851
- // HKCategoryValueSleepAnalysisAsleep is deprecated on iOS 16+ but still reported by older samples.
1852
- if (value == HKCategoryValueSleepAnalysisAsleep) {
1853
- return YES;
1854
- }
1855
- return NO;
1856
- }
1857
-
1858
- RCT_REMAP_METHOD(getTodayCalorieCount,
1859
- getTodayCalorieCountWithResolver:(RCTPromiseResolveBlock)resolve
1860
- rejecter:(RCTPromiseRejectBlock)reject)
1861
- {
1862
- if (![HKHealthStore isHealthDataAvailable]) {
1863
- reject(@"HEALTH_DATA_UNAVAILABLE", @"HealthKit is not available on this device", nil);
1864
- return;
1865
- }
1866
-
1867
- NSCalendar *cal = [NSCalendar currentCalendar];
1868
- NSDate *startOfDay = [cal startOfDayForDate:[NSDate date]];
1869
- NSDateComponents *dayInterval = [[NSDateComponents alloc] init];
1870
- dayInterval.day = 1;
1871
-
1872
- HKQuantityType *activeType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];
1873
- HKUnit *kcal = [HKUnit kilocalorieUnit];
1874
-
1875
- HKStatisticsCollectionQuery *query = [[HKStatisticsCollectionQuery alloc]
1876
- initWithQuantityType:activeType
1877
- quantitySamplePredicate:nil
1878
- options:HKStatisticsOptionCumulativeSum
1879
- anchorDate:startOfDay
1880
- intervalComponents:dayInterval];
1881
- query.initialResultsHandler = ^(HKStatisticsCollectionQuery *q,
1882
- HKStatisticsCollection *collection,
1883
- NSError *error) {
1884
- if (error) {
1885
- reject(@"CALORIE_QUERY_FAILED",
1886
- error.localizedDescription ?: @"Failed to query calorie data",
1887
- error);
1888
- return;
1889
- }
1890
- HKStatistics *todayStats = [collection statisticsForDate:startOfDay];
1891
- HKQuantity *sum = todayStats.sumQuantity;
1892
- NSInteger activeKcal = sum ? (NSInteger)[sum doubleValueForUnit:kcal] : 0;
1893
- resolve(@(activeKcal));
1894
- };
1895
- [[VisitRnSdkViewManager sharedManager] executeQuery:query];
1896
- }
1897
-
1898
1161
  RCT_REMAP_METHOD(triggerManualSync,
1899
1162
  triggerManualSyncWithResolver:(RCTPromiseResolveBlock)resolve
1900
1163
  rejecter:(RCTPromiseRejectBlock)reject)