react-native-visit-rn-sdk 3.0.5 → 3.0.6
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.
- package/README.md +91 -16
- package/ios/VisitRnSdkViewManager.h +6 -1
- package/ios/VisitRnSdkViewManager.m +760 -136
- package/lib/commonjs/index.ios.js +26 -40
- package/lib/commonjs/index.ios.js.map +1 -1
- package/lib/module/index.ios.js +29 -43
- package/lib/module/index.ios.js.map +1 -1
- package/package.json +1 -1
- package/src/index.ios.js +40 -58
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
#import "VisitRnSdkViewManager.h"
|
|
2
2
|
#import <HealthKit/HealthKit.h>
|
|
3
|
+
#import <UIKit/UIKit.h>
|
|
4
|
+
|
|
5
|
+
static NSString *const kVisitApiBaseUrlKey = @"visit_api_base_url";
|
|
6
|
+
static NSString *const kVisitAuthTokenKey = @"visit_auth_token";
|
|
7
|
+
static NSString *const kVisitHourlyLastSyncKey = @"gfHourlyLastSync";
|
|
8
|
+
static NSString *const kVisitDailyLastSyncKey = @"googleFitLastSync";
|
|
9
|
+
|
|
10
|
+
@interface VisitRnSdkViewManager ()
|
|
11
|
+
@property (atomic, assign) BOOL isSyncInProgress;
|
|
12
|
+
@end
|
|
3
13
|
|
|
4
14
|
@implementation VisitRnSdkViewManager
|
|
5
15
|
|
|
@@ -191,8 +201,10 @@ RCT_REMAP_METHOD(multiply,
|
|
|
191
201
|
|
|
192
202
|
- (void)fetchHourlySteps:(NSDate*) endDate callback:(void(^)(NSArray*))callback{
|
|
193
203
|
HKQuantityType *stepCountType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
|
|
204
|
+
HKQuantityType *activeEnergyType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];
|
|
194
205
|
NSCalendar *calendar = [NSCalendar currentCalendar];
|
|
195
206
|
HKUnit *stepsUnit = [HKUnit countUnit];
|
|
207
|
+
HKUnit *kcalUnit = [HKUnit kilocalorieUnit];
|
|
196
208
|
NSDateComponents *interval = [[NSDateComponents alloc] init];
|
|
197
209
|
interval.hour = 1;
|
|
198
210
|
NSDate *startDate = [[NSCalendar calendarWithIdentifier:NSCalendarIdentifierISO8601] startOfDayForDate:endDate];
|
|
@@ -204,46 +216,64 @@ RCT_REMAP_METHOD(multiply,
|
|
|
204
216
|
NSDate *anchorDate = [calendar startOfDayForDate:startDate];
|
|
205
217
|
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endOfDay options:HKQueryOptionStrictStartDate];
|
|
206
218
|
NSPredicate *userEnteredValuePredicate = [HKQuery predicateForObjectsWithMetadataKey:HKMetadataKeyWasUserEntered operatorType: NSNotEqualToPredicateOperatorType value: @YES];
|
|
207
|
-
|
|
219
|
+
|
|
208
220
|
NSCompoundPredicate *compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[predicate, userEnteredValuePredicate]];
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
221
|
+
|
|
222
|
+
dispatch_group_t group = dispatch_group_create();
|
|
223
|
+
NSMutableArray *stepsData = [NSMutableArray arrayWithCapacity:24];
|
|
224
|
+
NSMutableArray *calorieData = [NSMutableArray arrayWithCapacity:24];
|
|
225
|
+
|
|
226
|
+
dispatch_group_enter(group);
|
|
227
|
+
HKStatisticsCollectionQuery *stepsQuery = [[HKStatisticsCollectionQuery alloc]
|
|
228
|
+
initWithQuantityType:stepCountType
|
|
229
|
+
quantitySamplePredicate:compoundPredicate
|
|
230
|
+
options:HKStatisticsOptionCumulativeSum
|
|
231
|
+
anchorDate:anchorDate
|
|
232
|
+
intervalComponents:interval];
|
|
233
|
+
stepsQuery.initialResultsHandler = ^(HKStatisticsCollectionQuery *q,
|
|
234
|
+
HKStatisticsCollection *result,
|
|
235
|
+
NSError *error) {
|
|
213
236
|
if (error) {
|
|
214
|
-
NSLog(@"
|
|
215
|
-
|
|
216
|
-
|
|
237
|
+
NSLog(@"fetchHourlySteps steps query error: %@", error.localizedDescription);
|
|
238
|
+
} else {
|
|
239
|
+
[result enumerateStatisticsFromDate:startDate toDate:endOfDay
|
|
240
|
+
withBlock:^(HKStatistics *stat, BOOL *stop) {
|
|
241
|
+
HKQuantity *quantity = stat.sumQuantity;
|
|
242
|
+
int value = quantity ? (int)[quantity doubleValueForUnit:stepsUnit] : 0;
|
|
243
|
+
[stepsData addObject:@(value)];
|
|
244
|
+
}];
|
|
217
245
|
}
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
246
|
+
dispatch_group_leave(group);
|
|
247
|
+
};
|
|
248
|
+
[[VisitRnSdkViewManager sharedManager] executeQuery:stepsQuery];
|
|
249
|
+
|
|
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
|
+
}];
|
|
241
269
|
}
|
|
242
|
-
|
|
243
|
-
callback(finalData);
|
|
270
|
+
dispatch_group_leave(group);
|
|
244
271
|
};
|
|
245
|
-
|
|
246
|
-
|
|
272
|
+
[[VisitRnSdkViewManager sharedManager] executeQuery:caloriesQuery];
|
|
273
|
+
|
|
274
|
+
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
|
|
275
|
+
callback(@[stepsData, calorieData]);
|
|
276
|
+
});
|
|
247
277
|
}
|
|
248
278
|
|
|
249
279
|
-(void) fetchSteps:(NSString*) frequency endDate:(NSDate*) endDate days:(NSInteger) days callback:(void(^)(NSArray*))callback{
|
|
@@ -286,44 +316,67 @@ RCT_REMAP_METHOD(multiply,
|
|
|
286
316
|
NSLog(@"anchorComponents in fetchSteps are, %@",anchorComponents);
|
|
287
317
|
NSDate *anchorDate = [self->calendar dateFromComponents:anchorComponents];
|
|
288
318
|
NSLog(@"anchorDate in fetchSteps are, %@",anchorDate);
|
|
289
|
-
HKQuantityType *
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
319
|
+
HKQuantityType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
|
|
320
|
+
HKQuantityType *activeEnergyType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];
|
|
321
|
+
HKUnit *kcalUnit = [HKUnit kilocalorieUnit];
|
|
322
|
+
|
|
323
|
+
dispatch_group_t group = dispatch_group_create();
|
|
324
|
+
NSMutableArray *stepsData = [NSMutableArray new];
|
|
325
|
+
NSMutableArray *calorieData = [NSMutableArray new];
|
|
326
|
+
|
|
327
|
+
dispatch_group_enter(group);
|
|
328
|
+
HKStatisticsCollectionQuery *stepsQuery = [[HKStatisticsCollectionQuery alloc]
|
|
329
|
+
initWithQuantityType:stepType
|
|
330
|
+
quantitySamplePredicate:nil
|
|
331
|
+
options:HKStatisticsOptionCumulativeSum
|
|
332
|
+
anchorDate:anchorDate
|
|
333
|
+
intervalComponents:interval];
|
|
334
|
+
stepsQuery.initialResultsHandler = ^(HKStatisticsCollectionQuery *q,
|
|
335
|
+
HKStatisticsCollection *results,
|
|
336
|
+
NSError *error) {
|
|
299
337
|
if (error) {
|
|
300
|
-
|
|
301
|
-
|
|
338
|
+
NSLog(@"fetchSteps steps query error: %@", error.localizedDescription);
|
|
339
|
+
} else {
|
|
340
|
+
[results enumerateStatisticsFromDate:startDate
|
|
341
|
+
toDate:endDatePeriod
|
|
342
|
+
withBlock:^(HKStatistics *stat, BOOL *stop) {
|
|
343
|
+
HKQuantity *quantity = stat.sumQuantity;
|
|
344
|
+
int value = quantity ? (int)[quantity doubleValueForUnit:[HKUnit countUnit]] : 0;
|
|
345
|
+
[stepsData addObject:@(value)];
|
|
346
|
+
}];
|
|
302
347
|
}
|
|
303
|
-
|
|
304
|
-
NSMutableArray *calorieData = [NSMutableArray arrayWithCapacity:1];
|
|
305
|
-
[results enumerateStatisticsFromDate:startDate
|
|
306
|
-
toDate:endDatePeriod
|
|
307
|
-
withBlock:^(HKStatistics *result, BOOL *stop) {
|
|
308
|
-
|
|
309
|
-
HKQuantity *quantity = result.sumQuantity;
|
|
310
|
-
if (quantity) {
|
|
311
|
-
int value = [[NSNumber numberWithInt:[quantity doubleValueForUnit:[HKUnit countUnit]]] intValue];
|
|
312
|
-
int calories = value/21;
|
|
313
|
-
calories+=self->bmrCaloriesPerHour;
|
|
314
|
-
[calorieData addObject:[NSNumber numberWithInt:calories]];
|
|
315
|
-
[data addObject:[NSNumber numberWithInt:value]];
|
|
316
|
-
}else{
|
|
317
|
-
[data addObject:[NSNumber numberWithInt:0]];
|
|
318
|
-
[calorieData addObject:[NSNumber numberWithInt:0]];
|
|
319
|
-
}
|
|
320
|
-
}];
|
|
321
|
-
NSLog(@"in stepsData and calorieData is %@,%@", data, calorieData);
|
|
322
|
-
NSArray* finalData = @[data, calorieData];
|
|
323
|
-
callback(finalData);
|
|
348
|
+
dispatch_group_leave(group);
|
|
324
349
|
};
|
|
350
|
+
[[VisitRnSdkViewManager sharedManager] executeQuery:stepsQuery];
|
|
351
|
+
|
|
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];
|
|
325
376
|
|
|
326
|
-
|
|
377
|
+
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
|
|
378
|
+
callback(@[stepsData, calorieData]);
|
|
379
|
+
});
|
|
327
380
|
}
|
|
328
381
|
|
|
329
382
|
-(void) fetchHourlyDistanceWalkingRunning:(NSDate*) endDate callback:(void(^)(NSArray*))callback{
|
|
@@ -523,7 +576,9 @@ RCT_REMAP_METHOD(multiply,
|
|
|
523
576
|
NSArray *readTypes = @[[HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount],
|
|
524
577
|
[HKSampleType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis],
|
|
525
578
|
[HKSampleType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierBiologicalSex],
|
|
526
|
-
[HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning]
|
|
579
|
+
[HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning],
|
|
580
|
+
[HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned],
|
|
581
|
+
[HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierBasalEnergyBurned]];
|
|
527
582
|
|
|
528
583
|
[[VisitRnSdkViewManager sharedManager] requestAuthorizationToShareTypes:[NSSet setWithArray:writeTypes] readTypes:[NSSet setWithArray:readTypes]
|
|
529
584
|
completion:^(BOOL success, NSError *error) {
|
|
@@ -1069,7 +1124,11 @@ if([steps count]>0 && [distanceData count]>0 && [activityData count]>0 && [sleep
|
|
|
1069
1124
|
@"fitnessData" : dailySyncData,
|
|
1070
1125
|
};
|
|
1071
1126
|
callback(@[httpBody]);
|
|
1072
|
-
|
|
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(@[]);
|
|
1073
1132
|
}
|
|
1074
1133
|
});
|
|
1075
1134
|
}
|
|
@@ -1109,21 +1168,102 @@ if([steps count]>0 && [distanceData count]>0 && [activityData count]>0 && [sleep
|
|
|
1109
1168
|
|
|
1110
1169
|
RCT_EXPORT_METHOD(connectToAppleHealth:(RCTResponseSenderBlock)callback)
|
|
1111
1170
|
{
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1171
|
+
if (![HKHealthStore isHealthDataAvailable]) {
|
|
1172
|
+
callback(@[@{@"authStatus": @"UNAVAILABLE"}]);
|
|
1173
|
+
return;
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1176
|
+
HKObjectType *stepType =
|
|
1177
|
+
[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
|
|
1178
|
+
HKAuthorizationStatus preStatus =
|
|
1179
|
+
[[VisitRnSdkViewManager sharedManager] authorizationStatusForType:stepType];
|
|
1180
|
+
|
|
1181
|
+
// Match Android: report DENIED to JS and let the caller decide whether to
|
|
1182
|
+
// prompt the user (via Alert) to open the Health app. Do NOT open Health
|
|
1183
|
+
// ourselves — the JS side calls openAppleHealthApp on user confirmation.
|
|
1184
|
+
if (preStatus == HKAuthorizationStatusSharingDenied) {
|
|
1185
|
+
callback(@[@{@"authStatus": @"DENIED"}]);
|
|
1186
|
+
return;
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
NSSet *writeTypes =
|
|
1190
|
+
[NSSet setWithObject:[HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount]];
|
|
1191
|
+
NSSet *readTypes = [NSSet setWithArray:@[
|
|
1192
|
+
[HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount],
|
|
1193
|
+
[HKObjectType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis],
|
|
1194
|
+
[HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierBiologicalSex],
|
|
1195
|
+
[HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning],
|
|
1196
|
+
[HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned],
|
|
1197
|
+
[HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBasalEnergyBurned],
|
|
1198
|
+
]];
|
|
1199
|
+
|
|
1200
|
+
__weak typeof(self) weakSelf = self;
|
|
1201
|
+
[[VisitRnSdkViewManager sharedManager]
|
|
1202
|
+
requestAuthorizationToShareTypes:writeTypes
|
|
1203
|
+
readTypes:readTypes
|
|
1204
|
+
completion:^(BOOL success, NSError *error) {
|
|
1205
|
+
__strong typeof(weakSelf) strongSelf = weakSelf;
|
|
1206
|
+
if (!strongSelf) { return; }
|
|
1207
|
+
|
|
1208
|
+
dispatch_async(dispatch_get_main_queue(), ^{
|
|
1209
|
+
HKAuthorizationStatus postStatus =
|
|
1210
|
+
[[VisitRnSdkViewManager sharedManager] authorizationStatusForType:stepType];
|
|
1211
|
+
|
|
1212
|
+
if (postStatus == HKAuthorizationStatusSharingDenied) {
|
|
1213
|
+
callback(@[@{@"authStatus": @"DENIED"}]);
|
|
1214
|
+
return;
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
[strongSelf onHealthKitPermissionGranted:^(NSDictionary *data) {
|
|
1218
|
+
NSMutableDictionary *out =
|
|
1219
|
+
[NSMutableDictionary dictionaryWithDictionary:data ?: @{}];
|
|
1220
|
+
out[@"authStatus"] = @"GRANTED";
|
|
1221
|
+
callback(@[out]);
|
|
1222
|
+
}];
|
|
1223
|
+
});
|
|
1224
|
+
}];
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
// Opens Settings.app on the Health section (Settings → Health → Data Access
|
|
1228
|
+
// & Devices path). Uses the unofficial `App-Prefs:root=HEALTH` URL scheme
|
|
1229
|
+
// with a graceful fallback to `UIApplicationOpenSettingsURLString` (the
|
|
1230
|
+
// current app's Settings page) if iOS refuses the deep link. Vendors should
|
|
1231
|
+
// note the App Review caveat around `App-Prefs:` schemes documented in the
|
|
1232
|
+
// iOS vendor guide.
|
|
1233
|
+
RCT_EXPORT_METHOD(openAppleHealthApp:(RCTPromiseResolveBlock)resolve
|
|
1234
|
+
rejecter:(RCTPromiseRejectBlock)reject)
|
|
1235
|
+
{
|
|
1236
|
+
dispatch_async(dispatch_get_main_queue(), ^{
|
|
1237
|
+
UIApplication *app = [UIApplication sharedApplication];
|
|
1238
|
+
|
|
1239
|
+
void (^openAppSettings)(void) = ^{
|
|
1240
|
+
NSURL *settingsUrl = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
|
|
1241
|
+
if (!settingsUrl) {
|
|
1242
|
+
reject(@"OPEN_HEALTH_FAILED", @"Settings URL is unavailable", nil);
|
|
1243
|
+
return;
|
|
1244
|
+
}
|
|
1245
|
+
[app openURL:settingsUrl options:@{} completionHandler:^(BOOL success) {
|
|
1246
|
+
if (success) {
|
|
1247
|
+
resolve(@YES);
|
|
1248
|
+
} else {
|
|
1249
|
+
reject(@"OPEN_HEALTH_FAILED", @"Unable to open Settings app", nil);
|
|
1250
|
+
}
|
|
1251
|
+
}];
|
|
1252
|
+
};
|
|
1253
|
+
|
|
1254
|
+
NSURL *healthPrefsUrl = [NSURL URLWithString:@"App-Prefs:root=HEALTH"];
|
|
1255
|
+
if (!healthPrefsUrl) {
|
|
1256
|
+
openAppSettings();
|
|
1257
|
+
return;
|
|
1258
|
+
}
|
|
1259
|
+
[app openURL:healthPrefsUrl options:@{} completionHandler:^(BOOL success) {
|
|
1260
|
+
if (success) {
|
|
1261
|
+
resolve(@YES);
|
|
1262
|
+
} else {
|
|
1263
|
+
openAppSettings();
|
|
1264
|
+
}
|
|
1265
|
+
}];
|
|
1266
|
+
});
|
|
1127
1267
|
}
|
|
1128
1268
|
|
|
1129
1269
|
RCT_EXPORT_METHOD(renderGraph:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback)
|
|
@@ -1138,43 +1278,289 @@ RCT_EXPORT_METHOD(renderGraph:(NSDictionary *)input callback:(RCTResponseSenderB
|
|
|
1138
1278
|
}];
|
|
1139
1279
|
}
|
|
1140
1280
|
|
|
1281
|
+
- (void)postJSONBody:(NSDictionary *)body
|
|
1282
|
+
toURL:(NSString *)urlString
|
|
1283
|
+
authToken:(NSString *)authToken
|
|
1284
|
+
completion:(void (^)(NSError *error, NSInteger status))completion
|
|
1285
|
+
{
|
|
1286
|
+
NSURL *url = [NSURL URLWithString:urlString];
|
|
1287
|
+
if (!url) {
|
|
1288
|
+
completion([NSError errorWithDomain:@"VisitSync" code:-1
|
|
1289
|
+
userInfo:@{NSLocalizedDescriptionKey:
|
|
1290
|
+
[NSString stringWithFormat:@"Invalid URL: %@", urlString]}],
|
|
1291
|
+
0);
|
|
1292
|
+
return;
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1295
|
+
NSError *jsonError = nil;
|
|
1296
|
+
NSData *bodyData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&jsonError];
|
|
1297
|
+
if (jsonError) {
|
|
1298
|
+
completion(jsonError, 0);
|
|
1299
|
+
return;
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
|
|
1303
|
+
request.HTTPMethod = @"POST";
|
|
1304
|
+
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
|
|
1305
|
+
if (authToken.length > 0) {
|
|
1306
|
+
[request setValue:authToken forHTTPHeaderField:@"Authorization"];
|
|
1307
|
+
}
|
|
1308
|
+
request.HTTPBody = bodyData;
|
|
1309
|
+
|
|
1310
|
+
NSURLSessionDataTask *task =
|
|
1311
|
+
[[NSURLSession sharedSession] dataTaskWithRequest:request
|
|
1312
|
+
completionHandler:^(NSData *data,
|
|
1313
|
+
NSURLResponse *response,
|
|
1314
|
+
NSError *error) {
|
|
1315
|
+
NSInteger status = 0;
|
|
1316
|
+
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
|
|
1317
|
+
status = ((NSHTTPURLResponse *)response).statusCode;
|
|
1318
|
+
}
|
|
1319
|
+
completion(error, status);
|
|
1320
|
+
}];
|
|
1321
|
+
[task resume];
|
|
1322
|
+
}
|
|
1323
|
+
|
|
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.
|
|
1327
|
+
- (void)collectEmbellishBatchesForDates:(NSArray<NSDate *> *)dates
|
|
1328
|
+
completion:(void (^)(NSArray<NSDictionary *> *batches))completion
|
|
1329
|
+
{
|
|
1330
|
+
if (dates.count == 0) {
|
|
1331
|
+
completion(@[]);
|
|
1332
|
+
return;
|
|
1333
|
+
}
|
|
1334
|
+
|
|
1335
|
+
dispatch_group_t outer = dispatch_group_create();
|
|
1336
|
+
NSMutableArray<NSDictionary *> *batches = [NSMutableArray new];
|
|
1337
|
+
__weak typeof(self) weakSelf = self;
|
|
1338
|
+
|
|
1339
|
+
for (NSDate *date in dates) {
|
|
1340
|
+
dispatch_group_enter(outer);
|
|
1341
|
+
__block NSArray *steps = @[];
|
|
1342
|
+
__block NSArray *calories = @[];
|
|
1343
|
+
__block NSArray *distance = @[];
|
|
1344
|
+
dispatch_group_t inner = dispatch_group_create();
|
|
1345
|
+
|
|
1346
|
+
dispatch_group_enter(inner);
|
|
1347
|
+
[weakSelf fetchHourlySteps:date callback:^(NSArray *data) {
|
|
1348
|
+
if (data.count >= 2) {
|
|
1349
|
+
steps = data[0] ?: @[];
|
|
1350
|
+
calories = data[1] ?: @[];
|
|
1351
|
+
}
|
|
1352
|
+
dispatch_group_leave(inner);
|
|
1353
|
+
}];
|
|
1354
|
+
|
|
1355
|
+
dispatch_group_enter(inner);
|
|
1356
|
+
[weakSelf fetchHourlyDistanceWalkingRunning:date callback:^(NSArray *dist) {
|
|
1357
|
+
distance = dist ?: @[];
|
|
1358
|
+
dispatch_group_leave(inner);
|
|
1359
|
+
}];
|
|
1360
|
+
|
|
1361
|
+
dispatch_group_notify(inner,
|
|
1362
|
+
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
|
|
1363
|
+
__strong typeof(weakSelf) strongSelf = weakSelf;
|
|
1364
|
+
if (steps.count > 0 && calories.count > 0 && distance.count > 0 && strongSelf) {
|
|
1365
|
+
[strongSelf preprocessEmbellishRequest:steps
|
|
1366
|
+
calories:calories
|
|
1367
|
+
distance:distance
|
|
1368
|
+
date:date
|
|
1369
|
+
callback:^(NSArray *data) {
|
|
1370
|
+
if (data.count > 0 && [data[0] isKindOfClass:[NSDictionary class]]) {
|
|
1371
|
+
@synchronized (batches) {
|
|
1372
|
+
[batches addObject:data[0]];
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
dispatch_group_leave(outer);
|
|
1376
|
+
}];
|
|
1377
|
+
} else {
|
|
1378
|
+
dispatch_group_leave(outer);
|
|
1379
|
+
}
|
|
1380
|
+
});
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1383
|
+
dispatch_group_notify(outer, dispatch_get_main_queue(), ^{
|
|
1384
|
+
completion([batches copy]);
|
|
1385
|
+
});
|
|
1386
|
+
}
|
|
1387
|
+
|
|
1388
|
+
// Shared sync executor. Called from updateApiUrl (fire-and-forget) and
|
|
1389
|
+
// triggerManualSync (promise). Handles date-range → collection → HTTP POST for
|
|
1390
|
+
// both the embellish (hourly) and data-sync (daily) endpoints.
|
|
1391
|
+
- (void)performVisitSyncWithBaseUrl:(NSString *)baseUrl
|
|
1392
|
+
authToken:(NSString *)authToken
|
|
1393
|
+
hourlySince:(NSTimeInterval)gfHourlyLastSync
|
|
1394
|
+
dailySince:(NSTimeInterval)googleFitLastSync
|
|
1395
|
+
resolve:(RCTPromiseResolveBlock)resolve
|
|
1396
|
+
reject:(RCTPromiseRejectBlock)reject
|
|
1397
|
+
{
|
|
1398
|
+
NSDate *hourlyDataSyncTime = [NSDate dateWithTimeIntervalSince1970:gfHourlyLastSync / 1000];
|
|
1399
|
+
NSDate *dailyDataSyncTime = [NSDate dateWithTimeIntervalSince1970:googleFitLastSync / 1000];
|
|
1400
|
+
|
|
1401
|
+
NSString *embellishUrl = [NSString stringWithFormat:@"%@/users/embellish-sync", baseUrl];
|
|
1402
|
+
NSString *dataSyncUrl = [NSString stringWithFormat:@"%@/users/data-sync", baseUrl];
|
|
1403
|
+
|
|
1404
|
+
__block NSError *firstError = nil;
|
|
1405
|
+
NSLock *errorLock = [[NSLock alloc] init];
|
|
1406
|
+
void (^recordError)(NSError *) = ^(NSError *err) {
|
|
1407
|
+
if (!err) { return; }
|
|
1408
|
+
[errorLock lock];
|
|
1409
|
+
if (!firstError) { firstError = err; }
|
|
1410
|
+
[errorLock unlock];
|
|
1411
|
+
};
|
|
1412
|
+
|
|
1413
|
+
dispatch_group_t topGroup = dispatch_group_create();
|
|
1414
|
+
__weak typeof(self) weakSelf = self;
|
|
1415
|
+
|
|
1416
|
+
// Hourly / embellish flow
|
|
1417
|
+
dispatch_group_enter(topGroup);
|
|
1418
|
+
[self getDateRanges:hourlyDataSyncTime callback:^(NSMutableArray *dates) {
|
|
1419
|
+
__strong typeof(weakSelf) strongSelf = weakSelf;
|
|
1420
|
+
if (!strongSelf) {
|
|
1421
|
+
dispatch_group_leave(topGroup);
|
|
1422
|
+
return;
|
|
1423
|
+
}
|
|
1424
|
+
[strongSelf collectEmbellishBatchesForDates:dates
|
|
1425
|
+
completion:^(NSArray *batches) {
|
|
1426
|
+
if (batches.count == 0) {
|
|
1427
|
+
NSLog(@"[Visit Sync] no embellish batches to POST");
|
|
1428
|
+
dispatch_group_leave(topGroup);
|
|
1429
|
+
return;
|
|
1430
|
+
}
|
|
1431
|
+
dispatch_group_t postGroup = dispatch_group_create();
|
|
1432
|
+
for (NSDictionary *body in batches) {
|
|
1433
|
+
dispatch_group_enter(postGroup);
|
|
1434
|
+
[strongSelf postJSONBody:body
|
|
1435
|
+
toURL:embellishUrl
|
|
1436
|
+
authToken:authToken
|
|
1437
|
+
completion:^(NSError *err, NSInteger status) {
|
|
1438
|
+
NSLog(@"[Visit Sync] embellish POST status=%ld err=%@",
|
|
1439
|
+
(long)status, err.localizedDescription);
|
|
1440
|
+
if (err) {
|
|
1441
|
+
recordError(err);
|
|
1442
|
+
} else if (status < 200 || status >= 300) {
|
|
1443
|
+
recordError([NSError errorWithDomain:@"VisitSync"
|
|
1444
|
+
code:status
|
|
1445
|
+
userInfo:@{NSLocalizedDescriptionKey:
|
|
1446
|
+
[NSString stringWithFormat:
|
|
1447
|
+
@"embellish HTTP %ld",
|
|
1448
|
+
(long)status]}]);
|
|
1449
|
+
}
|
|
1450
|
+
dispatch_group_leave(postGroup);
|
|
1451
|
+
}];
|
|
1452
|
+
}
|
|
1453
|
+
dispatch_group_notify(postGroup,
|
|
1454
|
+
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
|
|
1455
|
+
dispatch_group_leave(topGroup);
|
|
1456
|
+
});
|
|
1457
|
+
}];
|
|
1458
|
+
}];
|
|
1459
|
+
|
|
1460
|
+
// Daily / data-sync flow
|
|
1461
|
+
dispatch_group_enter(topGroup);
|
|
1462
|
+
[self getDateRanges:dailyDataSyncTime callback:^(NSMutableArray *dates) {
|
|
1463
|
+
__strong typeof(weakSelf) strongSelf = weakSelf;
|
|
1464
|
+
if (!strongSelf || dates.count == 0) {
|
|
1465
|
+
dispatch_group_leave(topGroup);
|
|
1466
|
+
return;
|
|
1467
|
+
}
|
|
1468
|
+
[strongSelf callSyncData:dates.count
|
|
1469
|
+
dates:dates
|
|
1470
|
+
callback:^(NSArray *data) {
|
|
1471
|
+
if (data.count == 0 || ![data[0] isKindOfClass:[NSDictionary class]]) {
|
|
1472
|
+
NSLog(@"[Visit Sync] no daily sync payload to POST");
|
|
1473
|
+
dispatch_group_leave(topGroup);
|
|
1474
|
+
return;
|
|
1475
|
+
}
|
|
1476
|
+
[strongSelf postJSONBody:data[0]
|
|
1477
|
+
toURL:dataSyncUrl
|
|
1478
|
+
authToken:authToken
|
|
1479
|
+
completion:^(NSError *err, NSInteger status) {
|
|
1480
|
+
NSLog(@"[Visit Sync] data-sync POST status=%ld err=%@",
|
|
1481
|
+
(long)status, err.localizedDescription);
|
|
1482
|
+
if (err) {
|
|
1483
|
+
recordError(err);
|
|
1484
|
+
} else if (status < 200 || status >= 300) {
|
|
1485
|
+
recordError([NSError errorWithDomain:@"VisitSync"
|
|
1486
|
+
code:status
|
|
1487
|
+
userInfo:@{NSLocalizedDescriptionKey:
|
|
1488
|
+
[NSString stringWithFormat:
|
|
1489
|
+
@"data-sync HTTP %ld",
|
|
1490
|
+
(long)status]}]);
|
|
1491
|
+
}
|
|
1492
|
+
dispatch_group_leave(topGroup);
|
|
1493
|
+
}];
|
|
1494
|
+
}];
|
|
1495
|
+
}];
|
|
1496
|
+
|
|
1497
|
+
dispatch_group_notify(topGroup, dispatch_get_main_queue(), ^{
|
|
1498
|
+
self.isSyncInProgress = NO;
|
|
1499
|
+
if (firstError) {
|
|
1500
|
+
if (reject) {
|
|
1501
|
+
reject(@"SYNC_FAILED",
|
|
1502
|
+
firstError.localizedDescription ?: @"Sync failed",
|
|
1503
|
+
firstError);
|
|
1504
|
+
}
|
|
1505
|
+
} else {
|
|
1506
|
+
if (resolve) {
|
|
1507
|
+
resolve(@"Health Data Sync Completed");
|
|
1508
|
+
}
|
|
1509
|
+
}
|
|
1510
|
+
});
|
|
1511
|
+
}
|
|
1512
|
+
|
|
1141
1513
|
RCT_EXPORT_METHOD(updateApiUrl:(NSDictionary *)input)
|
|
1142
1514
|
{
|
|
1515
|
+
NSString *apiBaseUrl = [input objectForKey:@"apiBaseUrl"];
|
|
1516
|
+
NSString *authToken = [input objectForKey:@"authToken"];
|
|
1143
1517
|
NSTimeInterval gfHourlyLastSync = [[input objectForKey:@"gfHourlyLastSync"] doubleValue];
|
|
1144
1518
|
NSTimeInterval googleFitLastSync = [[input objectForKey:@"googleFitLastSync"] doubleValue];
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1519
|
+
|
|
1520
|
+
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
|
|
1521
|
+
if (apiBaseUrl.length > 0) {
|
|
1522
|
+
[defaults setObject:apiBaseUrl forKey:kVisitApiBaseUrlKey];
|
|
1523
|
+
}
|
|
1524
|
+
if (authToken.length > 0) {
|
|
1525
|
+
[defaults setObject:authToken forKey:kVisitAuthTokenKey];
|
|
1526
|
+
}
|
|
1527
|
+
if (gfHourlyLastSync > 0) {
|
|
1528
|
+
[defaults setDouble:gfHourlyLastSync forKey:kVisitHourlyLastSyncKey];
|
|
1529
|
+
}
|
|
1530
|
+
if (googleFitLastSync > 0) {
|
|
1531
|
+
[defaults setDouble:googleFitLastSync forKey:kVisitDailyLastSyncKey];
|
|
1532
|
+
}
|
|
1533
|
+
|
|
1534
|
+
NSString *storedBaseUrl = apiBaseUrl.length > 0 ? apiBaseUrl : [defaults stringForKey:kVisitApiBaseUrlKey];
|
|
1535
|
+
NSString *storedAuthToken = authToken.length > 0 ? authToken : [defaults stringForKey:kVisitAuthTokenKey];
|
|
1536
|
+
|
|
1537
|
+
if (![HKHealthStore isHealthDataAvailable]) {
|
|
1538
|
+
return;
|
|
1539
|
+
}
|
|
1540
|
+
if (storedBaseUrl.length == 0 || storedAuthToken.length == 0) {
|
|
1541
|
+
return;
|
|
1542
|
+
}
|
|
1543
|
+
if (self.isSyncInProgress) {
|
|
1544
|
+
return;
|
|
1545
|
+
}
|
|
1546
|
+
|
|
1547
|
+
self.isSyncInProgress = YES;
|
|
1548
|
+
__weak typeof(self) weakSelf = self;
|
|
1549
|
+
[self canAccessHealthKit:^(BOOL value) {
|
|
1550
|
+
__strong typeof(weakSelf) strongSelf = weakSelf;
|
|
1551
|
+
if (!strongSelf) { return; }
|
|
1552
|
+
if (!value) {
|
|
1553
|
+
strongSelf.isSyncInProgress = NO;
|
|
1554
|
+
[strongSelf requestAuthorization:^(NSDictionary *data) { (void)data; }];
|
|
1555
|
+
return;
|
|
1556
|
+
}
|
|
1557
|
+
[strongSelf performVisitSyncWithBaseUrl:storedBaseUrl
|
|
1558
|
+
authToken:storedAuthToken
|
|
1559
|
+
hourlySince:gfHourlyLastSync
|
|
1560
|
+
dailySince:googleFitLastSync
|
|
1561
|
+
resolve:nil
|
|
1562
|
+
reject:nil];
|
|
1563
|
+
}];
|
|
1178
1564
|
}
|
|
1179
1565
|
|
|
1180
1566
|
|
|
@@ -1285,25 +1671,263 @@ RCT_REMAP_METHOD(getHealthKitStatus,
|
|
|
1285
1671
|
}
|
|
1286
1672
|
}
|
|
1287
1673
|
|
|
1288
|
-
|
|
1674
|
+
RCT_REMAP_METHOD(requestHealthKitAuthorization,
|
|
1675
|
+
requestHealthKitAuthorizationWithResolver:(RCTPromiseResolveBlock)resolve
|
|
1676
|
+
rejecter:(RCTPromiseRejectBlock)reject)
|
|
1289
1677
|
{
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1678
|
+
if (![HKHealthStore isHealthDataAvailable]) {
|
|
1679
|
+
reject(@"HEALTH_DATA_UNAVAILABLE", @"HealthKit is not available on this device", nil);
|
|
1680
|
+
return;
|
|
1681
|
+
}
|
|
1682
|
+
|
|
1683
|
+
NSSet *writeTypes =
|
|
1684
|
+
[NSSet setWithObject:[HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount]];
|
|
1685
|
+
NSMutableSet *readTypes = [NSMutableSet setWithArray:@[
|
|
1686
|
+
[HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount],
|
|
1687
|
+
[HKObjectType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis],
|
|
1688
|
+
[HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierBiologicalSex],
|
|
1689
|
+
[HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning],
|
|
1690
|
+
[HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned],
|
|
1691
|
+
[HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBasalEnergyBurned],
|
|
1692
|
+
]];
|
|
1693
|
+
|
|
1694
|
+
[[VisitRnSdkViewManager sharedManager]
|
|
1695
|
+
requestAuthorizationToShareTypes:writeTypes
|
|
1696
|
+
readTypes:readTypes
|
|
1697
|
+
completion:^(BOOL success, NSError *error) {
|
|
1698
|
+
dispatch_async(dispatch_get_main_queue(), ^{
|
|
1699
|
+
if (!success) {
|
|
1700
|
+
reject(@"AUTHORIZATION_FAILED",
|
|
1701
|
+
error.localizedDescription ?: @"HealthKit authorization failed",
|
|
1702
|
+
error);
|
|
1703
|
+
return;
|
|
1704
|
+
}
|
|
1705
|
+
|
|
1706
|
+
HKObjectType *stepType =
|
|
1707
|
+
[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
|
|
1708
|
+
HKAuthorizationStatus status =
|
|
1709
|
+
[[VisitRnSdkViewManager sharedManager] authorizationStatusForType:stepType];
|
|
1710
|
+
|
|
1711
|
+
NSString *statusString;
|
|
1712
|
+
switch (status) {
|
|
1713
|
+
case HKAuthorizationStatusSharingAuthorized:
|
|
1714
|
+
statusString = @"GRANTED";
|
|
1715
|
+
break;
|
|
1716
|
+
case HKAuthorizationStatusSharingDenied:
|
|
1717
|
+
statusString = @"DENIED";
|
|
1718
|
+
break;
|
|
1719
|
+
case HKAuthorizationStatusNotDetermined:
|
|
1720
|
+
default:
|
|
1721
|
+
statusString = @"NOT_DETERMINED";
|
|
1722
|
+
break;
|
|
1723
|
+
}
|
|
1724
|
+
resolve(statusString);
|
|
1725
|
+
});
|
|
1726
|
+
}];
|
|
1727
|
+
}
|
|
1728
|
+
|
|
1729
|
+
RCT_REMAP_METHOD(getTodayStepCount,
|
|
1730
|
+
getTodayStepCountWithResolver:(RCTPromiseResolveBlock)resolve
|
|
1731
|
+
rejecter:(RCTPromiseRejectBlock)reject)
|
|
1732
|
+
{
|
|
1733
|
+
if (![HKHealthStore isHealthDataAvailable]) {
|
|
1734
|
+
reject(@"HEALTH_DATA_UNAVAILABLE", @"HealthKit is not available on this device", nil);
|
|
1735
|
+
return;
|
|
1736
|
+
}
|
|
1737
|
+
|
|
1738
|
+
NSCalendar *cal = [NSCalendar currentCalendar];
|
|
1739
|
+
NSDate *startOfDay = [cal startOfDayForDate:[NSDate date]];
|
|
1740
|
+
NSDateComponents *dayInterval = [[NSDateComponents alloc] init];
|
|
1741
|
+
dayInterval.day = 1;
|
|
1742
|
+
|
|
1743
|
+
HKQuantityType *stepType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
|
|
1744
|
+
|
|
1745
|
+
HKStatisticsCollectionQuery *query = [[HKStatisticsCollectionQuery alloc]
|
|
1746
|
+
initWithQuantityType:stepType
|
|
1747
|
+
quantitySamplePredicate:nil
|
|
1748
|
+
options:HKStatisticsOptionCumulativeSum
|
|
1749
|
+
anchorDate:startOfDay
|
|
1750
|
+
intervalComponents:dayInterval];
|
|
1751
|
+
|
|
1752
|
+
query.initialResultsHandler = ^(HKStatisticsCollectionQuery *q,
|
|
1753
|
+
HKStatisticsCollection *collection,
|
|
1754
|
+
NSError *error) {
|
|
1755
|
+
if (error) {
|
|
1756
|
+
reject(@"STEP_QUERY_FAILED",
|
|
1757
|
+
error.localizedDescription ?: @"Failed to query step count",
|
|
1758
|
+
error);
|
|
1759
|
+
return;
|
|
1760
|
+
}
|
|
1761
|
+
HKStatistics *todayStats = [collection statisticsForDate:startOfDay];
|
|
1762
|
+
HKQuantity *sum = todayStats.sumQuantity;
|
|
1763
|
+
NSInteger steps = sum ? (NSInteger)[sum doubleValueForUnit:[HKUnit countUnit]] : 0;
|
|
1764
|
+
resolve(@(steps));
|
|
1303
1765
|
};
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1766
|
+
|
|
1767
|
+
[[VisitRnSdkViewManager sharedManager] executeQuery:query];
|
|
1768
|
+
}
|
|
1769
|
+
|
|
1770
|
+
RCT_REMAP_METHOD(getTodaySleepMinutes,
|
|
1771
|
+
getTodaySleepMinutesWithResolver:(RCTPromiseResolveBlock)resolve
|
|
1772
|
+
rejecter:(RCTPromiseRejectBlock)reject)
|
|
1773
|
+
{
|
|
1774
|
+
if (![HKHealthStore isHealthDataAvailable]) {
|
|
1775
|
+
reject(@"HEALTH_DATA_UNAVAILABLE", @"HealthKit is not available on this device", nil);
|
|
1776
|
+
return;
|
|
1777
|
+
}
|
|
1778
|
+
|
|
1779
|
+
// Sum sleep sessions whose end date falls on today. Look 36 hours back so
|
|
1780
|
+
// overnight sessions (e.g., 11pm → 7am) that started yesterday are still
|
|
1781
|
+
// considered, matching Apple Health's "sleep on wake day" convention.
|
|
1782
|
+
NSCalendar *cal = [NSCalendar currentCalendar];
|
|
1783
|
+
NSDate *now = [NSDate date];
|
|
1784
|
+
NSDate *startOfDay = [cal startOfDayForDate:now];
|
|
1785
|
+
NSDate *lookbackStart = [now dateByAddingTimeInterval:-36 * 60 * 60];
|
|
1786
|
+
|
|
1787
|
+
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:lookbackStart
|
|
1788
|
+
endDate:now
|
|
1789
|
+
options:HKQueryOptionNone];
|
|
1790
|
+
HKCategoryType *sleepType = [HKObjectType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis];
|
|
1791
|
+
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierEndDate ascending:YES];
|
|
1792
|
+
|
|
1793
|
+
HKSampleQuery *query = [[HKSampleQuery alloc]
|
|
1794
|
+
initWithSampleType:sleepType
|
|
1795
|
+
predicate:predicate
|
|
1796
|
+
limit:HKObjectQueryNoLimit
|
|
1797
|
+
sortDescriptors:@[sort]
|
|
1798
|
+
resultsHandler:^(HKSampleQuery *q, NSArray<__kindof HKSample *> *results, NSError *error) {
|
|
1799
|
+
if (error) {
|
|
1800
|
+
reject(@"SLEEP_QUERY_FAILED", error.localizedDescription ?: @"Failed to query sleep data", error);
|
|
1801
|
+
return;
|
|
1802
|
+
}
|
|
1803
|
+
|
|
1804
|
+
NSTimeInterval totalSleepSeconds = 0;
|
|
1805
|
+
for (HKCategorySample *sample in results) {
|
|
1806
|
+
if (![self isAsleepSleepAnalysisValue:sample.value]) {
|
|
1807
|
+
continue;
|
|
1808
|
+
}
|
|
1809
|
+
// Only count samples that ended today.
|
|
1810
|
+
if ([sample.endDate compare:startOfDay] == NSOrderedAscending) {
|
|
1811
|
+
continue;
|
|
1812
|
+
}
|
|
1813
|
+
totalSleepSeconds += [sample.endDate timeIntervalSinceDate:sample.startDate];
|
|
1814
|
+
}
|
|
1815
|
+
NSInteger minutes = (NSInteger)(totalSleepSeconds / 60.0);
|
|
1816
|
+
resolve(@(minutes));
|
|
1817
|
+
}];
|
|
1818
|
+
|
|
1819
|
+
[[VisitRnSdkViewManager sharedManager] executeQuery:query];
|
|
1820
|
+
}
|
|
1821
|
+
|
|
1822
|
+
- (BOOL)isAsleepSleepAnalysisValue:(NSInteger)value
|
|
1823
|
+
{
|
|
1824
|
+
if (value == HKCategoryValueSleepAnalysisInBed) {
|
|
1825
|
+
return YES;
|
|
1826
|
+
}
|
|
1827
|
+
if (@available(iOS 16.0, *)) {
|
|
1828
|
+
if (value == HKCategoryValueSleepAnalysisAsleepUnspecified ||
|
|
1829
|
+
value == HKCategoryValueSleepAnalysisAsleepCore ||
|
|
1830
|
+
value == HKCategoryValueSleepAnalysisAsleepDeep ||
|
|
1831
|
+
value == HKCategoryValueSleepAnalysisAsleepREM) {
|
|
1832
|
+
return YES;
|
|
1833
|
+
}
|
|
1834
|
+
}
|
|
1835
|
+
// HKCategoryValueSleepAnalysisAsleep is deprecated on iOS 16+ but still reported by older samples.
|
|
1836
|
+
if (value == HKCategoryValueSleepAnalysisAsleep) {
|
|
1837
|
+
return YES;
|
|
1838
|
+
}
|
|
1839
|
+
return NO;
|
|
1840
|
+
}
|
|
1841
|
+
|
|
1842
|
+
RCT_REMAP_METHOD(getTodayCalorieCount,
|
|
1843
|
+
getTodayCalorieCountWithResolver:(RCTPromiseResolveBlock)resolve
|
|
1844
|
+
rejecter:(RCTPromiseRejectBlock)reject)
|
|
1845
|
+
{
|
|
1846
|
+
if (![HKHealthStore isHealthDataAvailable]) {
|
|
1847
|
+
reject(@"HEALTH_DATA_UNAVAILABLE", @"HealthKit is not available on this device", nil);
|
|
1848
|
+
return;
|
|
1849
|
+
}
|
|
1850
|
+
|
|
1851
|
+
NSCalendar *cal = [NSCalendar currentCalendar];
|
|
1852
|
+
NSDate *startOfDay = [cal startOfDayForDate:[NSDate date]];
|
|
1853
|
+
NSDateComponents *dayInterval = [[NSDateComponents alloc] init];
|
|
1854
|
+
dayInterval.day = 1;
|
|
1855
|
+
|
|
1856
|
+
HKQuantityType *activeType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];
|
|
1857
|
+
HKUnit *kcal = [HKUnit kilocalorieUnit];
|
|
1858
|
+
|
|
1859
|
+
HKStatisticsCollectionQuery *query = [[HKStatisticsCollectionQuery alloc]
|
|
1860
|
+
initWithQuantityType:activeType
|
|
1861
|
+
quantitySamplePredicate:nil
|
|
1862
|
+
options:HKStatisticsOptionCumulativeSum
|
|
1863
|
+
anchorDate:startOfDay
|
|
1864
|
+
intervalComponents:dayInterval];
|
|
1865
|
+
query.initialResultsHandler = ^(HKStatisticsCollectionQuery *q,
|
|
1866
|
+
HKStatisticsCollection *collection,
|
|
1867
|
+
NSError *error) {
|
|
1868
|
+
if (error) {
|
|
1869
|
+
reject(@"CALORIE_QUERY_FAILED",
|
|
1870
|
+
error.localizedDescription ?: @"Failed to query calorie data",
|
|
1871
|
+
error);
|
|
1872
|
+
return;
|
|
1873
|
+
}
|
|
1874
|
+
HKStatistics *todayStats = [collection statisticsForDate:startOfDay];
|
|
1875
|
+
HKQuantity *sum = todayStats.sumQuantity;
|
|
1876
|
+
NSInteger activeKcal = sum ? (NSInteger)[sum doubleValueForUnit:kcal] : 0;
|
|
1877
|
+
resolve(@(activeKcal));
|
|
1878
|
+
};
|
|
1879
|
+
[[VisitRnSdkViewManager sharedManager] executeQuery:query];
|
|
1880
|
+
}
|
|
1881
|
+
|
|
1882
|
+
RCT_REMAP_METHOD(triggerManualSync,
|
|
1883
|
+
triggerManualSyncWithResolver:(RCTPromiseResolveBlock)resolve
|
|
1884
|
+
rejecter:(RCTPromiseRejectBlock)reject)
|
|
1885
|
+
{
|
|
1886
|
+
if (![HKHealthStore isHealthDataAvailable]) {
|
|
1887
|
+
reject(@"HEALTH_DATA_UNAVAILABLE", @"HealthKit is not available on this device", nil);
|
|
1888
|
+
return;
|
|
1889
|
+
}
|
|
1890
|
+
if (self.isSyncInProgress) {
|
|
1891
|
+
reject(@"SYNC_IN_PROGRESS", @"Health data sync is already in progress", nil);
|
|
1892
|
+
return;
|
|
1893
|
+
}
|
|
1894
|
+
|
|
1895
|
+
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
|
|
1896
|
+
NSString *baseUrl = [defaults stringForKey:kVisitApiBaseUrlKey];
|
|
1897
|
+
NSString *authToken = [defaults stringForKey:kVisitAuthTokenKey];
|
|
1898
|
+
NSTimeInterval gfHourlyLastSync = [defaults doubleForKey:kVisitHourlyLastSyncKey];
|
|
1899
|
+
NSTimeInterval googleFitLastSync = [defaults doubleForKey:kVisitDailyLastSyncKey];
|
|
1900
|
+
|
|
1901
|
+
if (baseUrl.length == 0 || authToken.length == 0) {
|
|
1902
|
+
reject(@"MISSING_SYNC_CREDENTIALS",
|
|
1903
|
+
@"Visit apiBaseUrl or authToken is missing. Ensure the WebView has mounted at least once so credentials are seeded.",
|
|
1904
|
+
nil);
|
|
1905
|
+
return;
|
|
1906
|
+
}
|
|
1907
|
+
if (gfHourlyLastSync <= 0 && googleFitLastSync <= 0) {
|
|
1908
|
+
reject(@"MISSING_SYNC_TIMESTAMPS",
|
|
1909
|
+
@"Visit sync timestamps are missing. Ensure the WebView has run at least once.",
|
|
1910
|
+
nil);
|
|
1911
|
+
return;
|
|
1912
|
+
}
|
|
1913
|
+
|
|
1914
|
+
self.isSyncInProgress = YES;
|
|
1915
|
+
__weak typeof(self) weakSelf = self;
|
|
1916
|
+
[self canAccessHealthKit:^(BOOL value) {
|
|
1917
|
+
__strong typeof(weakSelf) strongSelf = weakSelf;
|
|
1918
|
+
if (!strongSelf) { return; }
|
|
1919
|
+
if (!value) {
|
|
1920
|
+
strongSelf.isSyncInProgress = NO;
|
|
1921
|
+
reject(@"PERMISSION_DENIED", @"HealthKit permission is not granted", nil);
|
|
1922
|
+
return;
|
|
1923
|
+
}
|
|
1924
|
+
[strongSelf performVisitSyncWithBaseUrl:baseUrl
|
|
1925
|
+
authToken:authToken
|
|
1926
|
+
hourlySince:gfHourlyLastSync
|
|
1927
|
+
dailySince:googleFitLastSync
|
|
1928
|
+
resolve:resolve
|
|
1929
|
+
reject:reject];
|
|
1930
|
+
}];
|
|
1307
1931
|
}
|
|
1308
1932
|
|
|
1309
1933
|
@end
|