react-native-visit-rn-sdk 6.0.3 → 7.0.0
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 +288 -122
- package/android/build.gradle +4 -1
- package/android/gradle.properties +4 -4
- package/android/src/main/AndroidManifest.xml +11 -5
- package/android/src/main/AndroidManifestNew.xml +11 -5
- package/android/src/main/java/com/visitrnsdk/VisitFitnessModule.kt +642 -0
- package/android/src/main/java/com/visitrnsdk/VisitRnSdkPackage.kt +1 -1
- package/android/src/main/java/com/visitrnsdk/VisitSessionStorage.kt +50 -0
- package/ios/VisitRnSdkViewManager.h +23 -1
- package/ios/VisitRnSdkViewManager.m +1259 -8
- package/lib/commonjs/Services.js +35 -0
- package/lib/commonjs/Services.js.map +1 -0
- package/lib/commonjs/constants.js +11 -0
- package/lib/commonjs/constants.js.map +1 -0
- package/lib/commonjs/index.android.js +450 -205
- package/lib/commonjs/index.android.js.map +1 -1
- package/lib/commonjs/index.ios.js +266 -114
- package/lib/commonjs/index.ios.js.map +1 -1
- package/lib/module/Services.js +27 -0
- package/lib/module/Services.js.map +1 -0
- package/lib/module/constants.js +5 -0
- package/lib/module/constants.js.map +1 -0
- package/lib/module/index.android.js +450 -206
- package/lib/module/index.android.js.map +1 -1
- package/lib/module/index.ios.js +268 -116
- package/lib/module/index.ios.js.map +1 -1
- package/lib/typescript/Services.d.ts +3 -0
- package/lib/typescript/Services.d.ts.map +1 -0
- package/lib/typescript/constants.d.ts +6 -0
- package/lib/typescript/constants.d.ts.map +1 -0
- package/lib/typescript/index.android.d.ts +26 -3
- package/lib/typescript/index.android.d.ts.map +1 -1
- package/lib/typescript/index.ios.d.ts +20 -3
- package/lib/typescript/index.ios.d.ts.map +1 -1
- package/package.json +14 -25
- package/react-native-visit-rn-sdk.podspec +2 -1
- package/src/Services.js +37 -0
- package/src/constants.js +4 -0
- package/src/index.android.js +773 -0
- package/src/index.ios.js +429 -0
- package/android/src/main/java/com/visitrnsdk/VisitRnSdkLocationModule.kt +0 -37
- package/lib/commonjs/assets/video-call/connecting-lottie.gif +0 -0
- package/lib/commonjs/assets/video-call/end-call.png +0 -0
- package/lib/commonjs/assets/video-call/mic-off.png +0 -0
- package/lib/commonjs/assets/video-call/reconnecting.gif +0 -0
- package/lib/commonjs/assets/video-call/switch-camera.png +0 -0
- package/lib/commonjs/assets/video-call/toggle-down.png +0 -0
- package/lib/commonjs/assets/video-call/toggle-up.png +0 -0
- package/lib/commonjs/assets/video-call/video-off.png +0 -0
- package/lib/commonjs/components/VideoCallComponent.js +0 -1088
- package/lib/commonjs/components/VideoCallComponent.js.map +0 -1
- package/lib/commonjs/index.js +0 -6
- package/lib/commonjs/index.js.map +0 -1
- package/lib/commonjs/shims.d.js +0 -2
- package/lib/commonjs/shims.d.js.map +0 -1
- package/lib/commonjs/types.js +0 -2
- package/lib/commonjs/types.js.map +0 -1
- package/lib/module/assets/video-call/connecting-lottie.gif +0 -0
- package/lib/module/assets/video-call/end-call.png +0 -0
- package/lib/module/assets/video-call/mic-off.png +0 -0
- package/lib/module/assets/video-call/reconnecting.gif +0 -0
- package/lib/module/assets/video-call/switch-camera.png +0 -0
- package/lib/module/assets/video-call/toggle-down.png +0 -0
- package/lib/module/assets/video-call/toggle-up.png +0 -0
- package/lib/module/assets/video-call/video-off.png +0 -0
- package/lib/module/components/VideoCallComponent.js +0 -1081
- package/lib/module/components/VideoCallComponent.js.map +0 -1
- package/lib/module/index.js +0 -2
- package/lib/module/index.js.map +0 -1
- package/lib/module/shims.d.js +0 -2
- package/lib/module/shims.d.js.map +0 -1
- package/lib/module/types.js +0 -2
- package/lib/module/types.js.map +0 -1
- package/lib/typescript/components/VideoCallComponent.d.ts +0 -79
- package/lib/typescript/components/VideoCallComponent.d.ts.map +0 -1
- package/lib/typescript/index.d.ts +0 -17
- package/lib/typescript/index.d.ts.map +0 -1
- package/lib/typescript/types.d.ts +0 -24
- package/lib/typescript/types.d.ts.map +0 -1
- package/src/assets/video-call/connecting-lottie.gif +0 -0
- package/src/assets/video-call/end-call.png +0 -0
- package/src/assets/video-call/mic-off.png +0 -0
- package/src/assets/video-call/reconnecting.gif +0 -0
- package/src/assets/video-call/switch-camera.png +0 -0
- package/src/assets/video-call/toggle-down.png +0 -0
- package/src/assets/video-call/toggle-up.png +0 -0
- package/src/assets/video-call/video-off.png +0 -0
- package/src/components/VideoCallComponent.tsx +0 -1484
- package/src/index.android.tsx +0 -459
- package/src/index.ios.tsx +0 -238
- package/src/index.tsx +0 -25
- package/src/shims.d.ts +0 -49
- package/src/types.ts +0 -25
|
@@ -1,23 +1,1274 @@
|
|
|
1
1
|
#import "VisitRnSdkViewManager.h"
|
|
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
|
+
static NSDateInterval *VisitFitnessDateInterval(NSCalendar *calendar, NSCalendarUnit unit, NSDate *date) {
|
|
11
|
+
NSDate *start;
|
|
12
|
+
NSTimeInterval duration;
|
|
13
|
+
[calendar rangeOfUnit:unit startDate:&start interval:&duration forDate:date];
|
|
14
|
+
return [[NSDateInterval alloc] initWithStartDate:start duration:duration];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
@interface VisitRnSdkViewManager ()
|
|
18
|
+
@property (atomic, assign) BOOL isSyncInProgress;
|
|
19
|
+
@end
|
|
2
20
|
|
|
3
21
|
@implementation VisitRnSdkViewManager
|
|
4
22
|
|
|
5
23
|
RCT_EXPORT_MODULE(VisitRnSdkViewManager)
|
|
6
24
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
return YES;
|
|
10
|
-
}
|
|
11
|
-
|
|
25
|
+
// Example method
|
|
26
|
+
// See // https://reactnative.dev/docs/native-modules-ios
|
|
12
27
|
RCT_REMAP_METHOD(multiply,
|
|
13
|
-
multiplyWithA:(nonnull NSNumber *)
|
|
14
|
-
withB:(nonnull NSNumber *)b
|
|
28
|
+
multiplyWithA:(nonnull NSNumber*)a withB:(nonnull NSNumber*)b
|
|
15
29
|
withResolver:(RCTPromiseResolveBlock)resolve
|
|
16
30
|
withRejecter:(RCTPromiseRejectBlock)reject)
|
|
17
31
|
{
|
|
18
|
-
(void)reject;
|
|
19
32
|
NSNumber *result = @([a floatValue] * [b floatValue]);
|
|
33
|
+
|
|
20
34
|
resolve(result);
|
|
21
35
|
}
|
|
22
36
|
|
|
37
|
+
- (instancetype)init
|
|
38
|
+
{
|
|
39
|
+
self = [super init];
|
|
40
|
+
self->calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierISO8601];
|
|
41
|
+
self->calendar.timeZone = [NSTimeZone timeZoneWithName:@"IST"];
|
|
42
|
+
NSLog(@"Do some stuff here");
|
|
43
|
+
return self;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
+ (BOOL)requiresMainQueueSetup{
|
|
47
|
+
return YES;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
+ (HKHealthStore *)sharedManager {
|
|
51
|
+
__strong static HKHealthStore *store = nil;
|
|
52
|
+
static dispatch_once_t onceToken;
|
|
53
|
+
dispatch_once(&onceToken, ^{
|
|
54
|
+
store = [[HKHealthStore alloc] init];
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
return store;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
- (NSArray<NSString *> *)supportedEvents
|
|
61
|
+
{
|
|
62
|
+
return @[@"EventReminder"];
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
- (void)fetchQuantitySamplesOfType:(HKQuantityType *)quantityType
|
|
66
|
+
unit:(HKUnit *)unit
|
|
67
|
+
predicate:(NSPredicate *)predicate
|
|
68
|
+
ascending:(BOOL)asc
|
|
69
|
+
limit:(NSUInteger)lim
|
|
70
|
+
completion:(void (^)(NSArray *, NSError *))completion {
|
|
71
|
+
|
|
72
|
+
NSSortDescriptor *timeSortDescriptor = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierEndDate
|
|
73
|
+
ascending:asc];
|
|
74
|
+
__block NSTimeInterval totalActivityDuration = 0;
|
|
75
|
+
// declare the block
|
|
76
|
+
void (^handlerBlock)(HKSampleQuery *query, NSArray *results, NSError *error);
|
|
77
|
+
// create and assign the block
|
|
78
|
+
handlerBlock = ^(HKSampleQuery *query, NSArray *results, NSError *error) {
|
|
79
|
+
if (!results) {
|
|
80
|
+
if (completion) {
|
|
81
|
+
completion(nil, error);
|
|
82
|
+
}
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
if (completion) {
|
|
87
|
+
NSMutableArray *data = [NSMutableArray arrayWithCapacity:1];
|
|
88
|
+
NSMutableArray *dataByFrequency = [NSMutableArray new];
|
|
89
|
+
dispatch_async(dispatch_get_main_queue(), ^{
|
|
90
|
+
for (HKQuantitySample *sample in results) {
|
|
91
|
+
HKQuantity *quantity = sample.quantity;
|
|
92
|
+
double value = [quantity doubleValueForUnit:unit];
|
|
93
|
+
if(value){
|
|
94
|
+
NSLog(@"startDate and endDate for fetchQuantitySamplesOfType is %@ & %@", sample.startDate,sample.endDate);
|
|
95
|
+
NSNumber* val = [NSNumber numberWithDouble:[sample.endDate timeIntervalSinceDate:sample.startDate]/60];
|
|
96
|
+
NSDictionary *element = @{
|
|
97
|
+
@"date" : sample.endDate,
|
|
98
|
+
@"value" : val,
|
|
99
|
+
};
|
|
100
|
+
NSMutableDictionary *dict =[NSMutableDictionary dictionaryWithDictionary:element];
|
|
101
|
+
|
|
102
|
+
if([dataByFrequency count]>0){
|
|
103
|
+
NSMutableDictionary* ele = [dataByFrequency objectAtIndex:[dataByFrequency count]-1];
|
|
104
|
+
if([[NSCalendar currentCalendar] isDate:sample.endDate inSameDayAsDate:[ele valueForKey:@"date"]]){
|
|
105
|
+
double myValue = [[ele valueForKey:@"value"] doubleValue];
|
|
106
|
+
myValue+=[val doubleValue];
|
|
107
|
+
[ele setObject:sample.endDate forKey:@"date" ];
|
|
108
|
+
[ele setObject: [NSNumber numberWithDouble:myValue] forKey:@"value" ];
|
|
109
|
+
}else{
|
|
110
|
+
[dataByFrequency addObject:dict];
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
else{
|
|
114
|
+
[dataByFrequency addObject:dict];
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
NSTimeInterval duration = [sample.endDate timeIntervalSinceDate:sample.startDate];
|
|
118
|
+
totalActivityDuration+=duration;
|
|
119
|
+
NSLog(@"fetchQuantitySamplesOfType dict is %@",dict);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
NSLog(@"fetchQuantitySamplesOfType dataByFrequency %@ ",dataByFrequency);
|
|
123
|
+
[data addObject:[NSString stringWithFormat:@"%f",totalActivityDuration/60]];
|
|
124
|
+
[data addObject:dataByFrequency];
|
|
125
|
+
completion(data, error);
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:quantityType
|
|
131
|
+
predicate:predicate
|
|
132
|
+
limit:lim
|
|
133
|
+
sortDescriptors:@[timeSortDescriptor]
|
|
134
|
+
resultsHandler:handlerBlock];
|
|
135
|
+
|
|
136
|
+
[[VisitRnSdkViewManager sharedManager] executeQuery:query];
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
- (void) getActivityTime:(NSDate*) endDate frequency:(NSString*) frequency days:(NSInteger) days callback:(void(^)(NSMutableArray*))callback{
|
|
141
|
+
HKQuantityType *stepCountType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
|
|
142
|
+
NSDate *startDate;
|
|
143
|
+
NSDate *endDatePeriod;
|
|
144
|
+
if([frequency isEqualToString:@"day"]){
|
|
145
|
+
NSTimeInterval interval;
|
|
146
|
+
[self->calendar rangeOfUnit:NSCalendarUnitDay
|
|
147
|
+
startDate:&startDate
|
|
148
|
+
interval:&interval
|
|
149
|
+
forDate:endDate];
|
|
150
|
+
endDatePeriod = [startDate dateByAddingTimeInterval:interval-1];
|
|
151
|
+
}else if ([frequency isEqualToString:@"week"]){
|
|
152
|
+
NSTimeInterval interval;
|
|
153
|
+
[self->calendar rangeOfUnit:NSCalendarUnitWeekOfYear
|
|
154
|
+
startDate:&startDate
|
|
155
|
+
interval:&interval
|
|
156
|
+
forDate:endDate];
|
|
157
|
+
endDatePeriod = [startDate dateByAddingTimeInterval:interval-1];
|
|
158
|
+
}else if ([frequency isEqualToString:@"month"]){
|
|
159
|
+
NSTimeInterval interval;
|
|
160
|
+
[self->calendar rangeOfUnit:NSCalendarUnitMonth
|
|
161
|
+
startDate:&startDate
|
|
162
|
+
interval:&interval
|
|
163
|
+
forDate:endDate];
|
|
164
|
+
endDatePeriod = [startDate dateByAddingTimeInterval:interval-1];
|
|
165
|
+
}else if([frequency isEqualToString:@"custom"]){
|
|
166
|
+
endDatePeriod = endDate;
|
|
167
|
+
startDate = [self->calendar dateByAddingUnit:NSCalendarUnitDay
|
|
168
|
+
value:1-days
|
|
169
|
+
toDate:endDatePeriod
|
|
170
|
+
options:0];
|
|
171
|
+
}
|
|
172
|
+
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDatePeriod options:HKQueryOptionStrictStartDate];
|
|
173
|
+
NSPredicate *userEnteredValuePredicate = [HKQuery predicateForObjectsWithMetadataKey:HKMetadataKeyWasUserEntered operatorType: NSNotEqualToPredicateOperatorType value: @YES];
|
|
174
|
+
|
|
175
|
+
NSCompoundPredicate *compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[predicate, userEnteredValuePredicate]];
|
|
176
|
+
[self fetchQuantitySamplesOfType:stepCountType unit:[HKUnit countUnit] predicate:compoundPredicate ascending:true limit:HKObjectQueryNoLimit completion:^(NSArray *results, NSError *error) {
|
|
177
|
+
if (results) {
|
|
178
|
+
NSLog(@"the results of getActivityTime %@",results);
|
|
179
|
+
callback([NSMutableArray arrayWithArray:results]);
|
|
180
|
+
return;
|
|
181
|
+
} else {
|
|
182
|
+
NSLog(@"error getting step count samples: %@", error);
|
|
183
|
+
callback([NSMutableArray arrayWithArray:@[@"0", @[]]]);
|
|
184
|
+
}
|
|
185
|
+
}];
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
- (NSSet<HKObjectType *> *)fitnessReadTypes {
|
|
189
|
+
return [NSSet setWithArray:@[
|
|
190
|
+
[HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount],
|
|
191
|
+
[HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning],
|
|
192
|
+
[HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned],
|
|
193
|
+
[HKCategoryType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis],
|
|
194
|
+
]];
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
- (void)fetchFitnessBuckets:(NSString *)metric
|
|
198
|
+
start:(NSDate *)start
|
|
199
|
+
end:(NSDate *)end
|
|
200
|
+
hourly:(BOOL)hourly
|
|
201
|
+
completion:(void (^)(NSArray<NSNumber *> *, NSError *))completion {
|
|
202
|
+
if ([start compare:end] == NSOrderedDescending) {
|
|
203
|
+
completion(@[], nil);
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
HKQuantityTypeIdentifier identifier = HKQuantityTypeIdentifierStepCount;
|
|
208
|
+
HKUnit *unit = [HKUnit countUnit];
|
|
209
|
+
if ([metric isEqualToString:@"calories"]) {
|
|
210
|
+
identifier = HKQuantityTypeIdentifierActiveEnergyBurned;
|
|
211
|
+
unit = [HKUnit kilocalorieUnit];
|
|
212
|
+
} else if ([metric isEqualToString:@"distance"]) {
|
|
213
|
+
identifier = HKQuantityTypeIdentifierDistanceWalkingRunning;
|
|
214
|
+
unit = [HKUnit meterUnit];
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
NSCalendar *bucketCalendar = self->calendar;
|
|
218
|
+
NSDate *anchor = [bucketCalendar startOfDayForDate:start];
|
|
219
|
+
NSDateComponents *interval = [NSDateComponents new];
|
|
220
|
+
if (hourly) {
|
|
221
|
+
interval.hour = 1;
|
|
222
|
+
} else {
|
|
223
|
+
interval.day = 1;
|
|
224
|
+
}
|
|
225
|
+
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:start
|
|
226
|
+
endDate:end
|
|
227
|
+
options:HKQueryOptionNone];
|
|
228
|
+
if (hourly && [metric isEqualToString:@"steps"]) {
|
|
229
|
+
NSPredicate *automatic = [HKQuery predicateForObjectsWithMetadataKey:HKMetadataKeyWasUserEntered
|
|
230
|
+
operatorType:NSNotEqualToPredicateOperatorType
|
|
231
|
+
value:@YES];
|
|
232
|
+
predicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[predicate, automatic]];
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
HKQuantityType *type = [HKQuantityType quantityTypeForIdentifier:identifier];
|
|
236
|
+
HKStatisticsCollectionQuery *query = [[HKStatisticsCollectionQuery alloc]
|
|
237
|
+
initWithQuantityType:type
|
|
238
|
+
quantitySamplePredicate:predicate
|
|
239
|
+
options:HKStatisticsOptionCumulativeSum
|
|
240
|
+
anchorDate:anchor
|
|
241
|
+
intervalComponents:interval];
|
|
242
|
+
query.initialResultsHandler = ^(HKStatisticsCollectionQuery *query,
|
|
243
|
+
HKStatisticsCollection *results,
|
|
244
|
+
NSError *error) {
|
|
245
|
+
if (error) {
|
|
246
|
+
completion(@[], error);
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
NSMutableArray<NSNumber *> *values = [NSMutableArray new];
|
|
250
|
+
if (hourly) {
|
|
251
|
+
for (NSInteger hour = 0; hour < 24; hour++) {
|
|
252
|
+
[values addObject:@0];
|
|
253
|
+
}
|
|
254
|
+
[results enumerateStatisticsFromDate:start toDate:end withBlock:^(HKStatistics *stat, BOOL *stop) {
|
|
255
|
+
NSInteger hour = [bucketCalendar component:NSCalendarUnitHour fromDate:stat.startDate];
|
|
256
|
+
double value = [stat.sumQuantity doubleValueForUnit:unit];
|
|
257
|
+
values[hour] = @(values[hour].doubleValue + value);
|
|
258
|
+
}];
|
|
259
|
+
} else {
|
|
260
|
+
NSDate *lastDay = [bucketCalendar startOfDayForDate:end];
|
|
261
|
+
for (NSDate *day = anchor; [day compare:lastDay] != NSOrderedDescending;
|
|
262
|
+
day = [bucketCalendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:day options:0]) {
|
|
263
|
+
HKStatistics *stat = [results statisticsForDate:day];
|
|
264
|
+
[values addObject:@((NSInteger)[stat.sumQuantity doubleValueForUnit:unit])];
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
completion([values copy], error);
|
|
268
|
+
};
|
|
269
|
+
[[VisitRnSdkViewManager sharedManager] executeQuery:query];
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
- (void)fetchHourlyFitnessForDate:(NSDate *)date
|
|
273
|
+
completion:(void (^)(NSArray<NSNumber *> *, NSArray<NSNumber *> *, NSArray<NSNumber *> *))completion {
|
|
274
|
+
NSDateInterval *day = VisitFitnessDateInterval(self->calendar, NSCalendarUnitDay, date);
|
|
275
|
+
NSDate *end = [day.endDate dateByAddingTimeInterval:-1];
|
|
276
|
+
NSArray<NSString *> *metrics = @[@"steps", @"calories", @"distance"];
|
|
277
|
+
NSMutableDictionary<NSString *, NSArray<NSNumber *> *> *series = [NSMutableDictionary new];
|
|
278
|
+
dispatch_group_t group = dispatch_group_create();
|
|
279
|
+
for (NSString *metric in metrics) {
|
|
280
|
+
dispatch_group_enter(group);
|
|
281
|
+
[self fetchFitnessBuckets:metric start:day.startDate end:end hourly:YES
|
|
282
|
+
completion:^(NSArray<NSNumber *> *values, NSError *error) {
|
|
283
|
+
if (error) NSLog(@"HealthKit %@ query failed: %@", metric, error.localizedDescription);
|
|
284
|
+
@synchronized (series) { if (!error) series[metric] = values; }
|
|
285
|
+
dispatch_group_leave(group);
|
|
286
|
+
}];
|
|
287
|
+
}
|
|
288
|
+
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
|
|
289
|
+
completion(series[@"steps"], series[@"calories"], series[@"distance"]);
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
- (void)fetchSleepFromDay:(NSDate *)firstDay
|
|
294
|
+
throughDay:(NSDate *)lastDay
|
|
295
|
+
completion:(void (^)(NSDictionary<NSDate *, NSArray<NSDateInterval *> *> *, NSError *))completion {
|
|
296
|
+
NSCalendar *sleepCalendar = self->calendar;
|
|
297
|
+
NSDate *end = [sleepCalendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:lastDay options:0];
|
|
298
|
+
NSDate *lookback = [firstDay dateByAddingTimeInterval:-36 * 60 * 60];
|
|
299
|
+
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:lookback endDate:end options:HKQueryOptionNone];
|
|
300
|
+
HKCategoryType *type = [HKCategoryType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis];
|
|
301
|
+
NSSortDescriptor *byStart = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:YES];
|
|
302
|
+
HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:type
|
|
303
|
+
predicate:predicate
|
|
304
|
+
limit:HKObjectQueryNoLimit
|
|
305
|
+
sortDescriptors:@[byStart]
|
|
306
|
+
resultsHandler:^(HKSampleQuery *query,
|
|
307
|
+
NSArray<__kindof HKSample *> *samples,
|
|
308
|
+
NSError *error) {
|
|
309
|
+
NSMutableDictionary<NSDate *, NSMutableArray<NSDateInterval *> *> *asleep = [NSMutableDictionary new];
|
|
310
|
+
NSMutableDictionary<NSDate *, NSMutableArray<NSDateInterval *> *> *inBed = [NSMutableDictionary new];
|
|
311
|
+
for (HKCategorySample *sample in samples) {
|
|
312
|
+
NSDate *day = [sleepCalendar startOfDayForDate:sample.endDate];
|
|
313
|
+
if ([day compare:firstDay] == NSOrderedAscending || [day compare:lastDay] == NSOrderedDescending ||
|
|
314
|
+
[sample.startDate compare:sample.endDate] != NSOrderedAscending) {
|
|
315
|
+
continue;
|
|
316
|
+
}
|
|
317
|
+
NSMutableDictionary<NSDate *, NSMutableArray<NSDateInterval *> *> *target;
|
|
318
|
+
if (sample.value == HKCategoryValueSleepAnalysisInBed) {
|
|
319
|
+
target = inBed;
|
|
320
|
+
} else if (sample.value == HKCategoryValueSleepAnalysisAwake) {
|
|
321
|
+
continue;
|
|
322
|
+
} else {
|
|
323
|
+
target = asleep;
|
|
324
|
+
}
|
|
325
|
+
NSMutableArray<NSDateInterval *> *intervals = target[day];
|
|
326
|
+
if (!intervals) {
|
|
327
|
+
intervals = [NSMutableArray new];
|
|
328
|
+
target[day] = intervals;
|
|
329
|
+
}
|
|
330
|
+
NSDateInterval *previous = intervals.lastObject;
|
|
331
|
+
if (previous && [sample.startDate compare:previous.endDate] != NSOrderedDescending) {
|
|
332
|
+
NSDate *latestEnd = [previous.endDate laterDate:sample.endDate];
|
|
333
|
+
intervals[intervals.count - 1] = [[NSDateInterval alloc] initWithStartDate:previous.startDate endDate:latestEnd];
|
|
334
|
+
} else {
|
|
335
|
+
[intervals addObject:[[NSDateInterval alloc] initWithStartDate:sample.startDate endDate:sample.endDate]];
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
// In-bed-only sources still provide a sleep window. Prefer actual
|
|
339
|
+
// asleep samples when both exist on the same wake day.
|
|
340
|
+
NSMutableDictionary *sleepByDay = [inBed mutableCopy];
|
|
341
|
+
[sleepByDay addEntriesFromDictionary:asleep];
|
|
342
|
+
completion(sleepByDay, error);
|
|
343
|
+
}];
|
|
344
|
+
[[VisitRnSdkViewManager sharedManager] executeQuery:query];
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
- (void)fetchTodaySleepMinutes:(void (^)(NSNumber *, NSError *))completion {
|
|
348
|
+
NSDate *today = [self->calendar startOfDayForDate:[NSDate date]];
|
|
349
|
+
[self fetchSleepFromDay:today throughDay:today
|
|
350
|
+
completion:^(NSDictionary<NSDate *, NSArray<NSDateInterval *> *> *sleepByDay, NSError *error) {
|
|
351
|
+
NSTimeInterval seconds = 0;
|
|
352
|
+
for (NSDateInterval *interval in sleepByDay[today]) {
|
|
353
|
+
seconds += interval.duration;
|
|
354
|
+
}
|
|
355
|
+
completion(@((NSInteger)(seconds / 60)), error);
|
|
356
|
+
}];
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
- (void)requestAuthorization:(void(^)(NSDictionary*))callback {
|
|
360
|
+
|
|
361
|
+
if ([HKHealthStore isHealthDataAvailable] == NO) {
|
|
362
|
+
// If our device doesn't support HealthKit -> return.
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
[[VisitRnSdkViewManager sharedManager] requestAuthorizationToShareTypes:nil readTypes:[self fitnessReadTypes]
|
|
366
|
+
completion:^(BOOL success, NSError *error) {
|
|
367
|
+
NSLog(@"requestAuthorizationToShareTypes executed");
|
|
368
|
+
[self canAccessHealthKit:^(BOOL value){
|
|
369
|
+
if(value){
|
|
370
|
+
NSLog(@"the health kit permission granted");
|
|
371
|
+
[self onHealthKitPermissionGranted:^(NSDictionary * data) {
|
|
372
|
+
callback(data);
|
|
373
|
+
}];
|
|
374
|
+
}else{
|
|
375
|
+
NSLog(@"the health kit permission not granted");
|
|
376
|
+
}
|
|
377
|
+
}];
|
|
378
|
+
}];
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
- (void)onHealthKitPermissionGranted:(void (^)(NSDictionary *))callback {
|
|
382
|
+
NSDate *now = [NSDate date];
|
|
383
|
+
NSDate *today = [self->calendar startOfDayForDate:now];
|
|
384
|
+
[self fetchFitnessBuckets:@"steps" start:today end:now hourly:NO
|
|
385
|
+
completion:^(NSArray<NSNumber *> *steps, NSError *stepsError) {
|
|
386
|
+
[self fetchTodaySleepMinutes:^(NSNumber *minutes, NSError *sleepError) {
|
|
387
|
+
NSDictionary *result = @{@"numberOfSteps": steps.firstObject ?: @0, @"sleepTime": minutes};
|
|
388
|
+
dispatch_async(dispatch_get_main_queue(), ^{
|
|
389
|
+
self->hasLoadedOnce = true;
|
|
390
|
+
callback(result);
|
|
391
|
+
});
|
|
392
|
+
}];
|
|
393
|
+
}];
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
-(void) healthKitRequestStatus:(void(^)(HKAuthorizationRequestStatus))callback {
|
|
397
|
+
if (![HKHealthStore isHealthDataAvailable]) {
|
|
398
|
+
callback(HKAuthorizationRequestStatusUnknown);
|
|
399
|
+
return;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
NSSet *readTypes = [self fitnessReadTypes];
|
|
403
|
+
|
|
404
|
+
[[VisitRnSdkViewManager sharedManager]
|
|
405
|
+
getRequestStatusForAuthorizationToShareTypes:[NSSet set]
|
|
406
|
+
readTypes:readTypes
|
|
407
|
+
completion:^(HKAuthorizationRequestStatus status,
|
|
408
|
+
NSError *error) {
|
|
409
|
+
if (error) {
|
|
410
|
+
NSLog(@"healthKitRequestStatus error: %@", error.localizedDescription);
|
|
411
|
+
}
|
|
412
|
+
callback(status);
|
|
413
|
+
}];
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
- (void)hasReadableFitnessSamples:(void (^)(BOOL))callback {
|
|
417
|
+
if (![HKHealthStore isHealthDataAvailable]) {
|
|
418
|
+
callback(NO);
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
dispatch_group_t group = dispatch_group_create();
|
|
423
|
+
NSObject *lock = [NSObject new];
|
|
424
|
+
__block BOOL found = NO;
|
|
425
|
+
for (HKSampleType *type in [self fitnessReadTypes]) {
|
|
426
|
+
dispatch_group_enter(group);
|
|
427
|
+
HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:type
|
|
428
|
+
predicate:nil
|
|
429
|
+
limit:1
|
|
430
|
+
sortDescriptors:nil
|
|
431
|
+
resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {
|
|
432
|
+
if (results.count > 0) {
|
|
433
|
+
@synchronized (lock) { found = YES; }
|
|
434
|
+
}
|
|
435
|
+
dispatch_group_leave(group);
|
|
436
|
+
}];
|
|
437
|
+
[[VisitRnSdkViewManager sharedManager] executeQuery:query];
|
|
438
|
+
}
|
|
439
|
+
dispatch_group_notify(group, dispatch_get_main_queue(), ^{ callback(found); });
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
-(void) canAccessHealthKit: (void(^)(BOOL))callback {
|
|
443
|
+
__weak typeof(self) weakSelf = self;
|
|
444
|
+
[self healthKitRequestStatus:^(HKAuthorizationRequestStatus status) {
|
|
445
|
+
__strong typeof(weakSelf) strongSelf = weakSelf;
|
|
446
|
+
if (!strongSelf || status != HKAuthorizationRequestStatusUnnecessary) {
|
|
447
|
+
callback(NO);
|
|
448
|
+
return;
|
|
449
|
+
}
|
|
450
|
+
[strongSelf hasReadableFitnessSamples:callback];
|
|
451
|
+
}];
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
static NSNumber *VisitHealthTimestamp(NSDate *date) {
|
|
455
|
+
return @((long long)([date timeIntervalSince1970] * 1000));
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
- (void)renderGraphData:(NSString *)type frequency:(NSString *)frequency date:(NSDate *)date callback:(void (^)(NSArray *))callback {
|
|
459
|
+
BOOL isDay = [frequency isEqualToString:@"day"];
|
|
460
|
+
BOOL isWeek = [frequency isEqualToString:@"week"];
|
|
461
|
+
BOOL isMonth = [frequency isEqualToString:@"month"];
|
|
462
|
+
if (!isDay && !isWeek && !isMonth) {
|
|
463
|
+
callback(@[]);
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
NSCalendar *graphCalendar = self->calendar;
|
|
468
|
+
NSCalendarUnit unit = isDay ? NSCalendarUnitDay : (isWeek ? NSCalendarUnitWeekOfYear : NSCalendarUnitMonth);
|
|
469
|
+
NSDateInterval *range = VisitFitnessDateInterval(graphCalendar, unit, date);
|
|
470
|
+
NSDate *end = [range.endDate dateByAddingTimeInterval:-1];
|
|
471
|
+
|
|
472
|
+
if ([type isEqualToString:@"sleep"]) {
|
|
473
|
+
if (isMonth) {
|
|
474
|
+
callback(@[]);
|
|
475
|
+
return;
|
|
476
|
+
}
|
|
477
|
+
NSDate *lastDay = [graphCalendar startOfDayForDate:end];
|
|
478
|
+
[self fetchSleepFromDay:range.startDate throughDay:lastDay
|
|
479
|
+
completion:^(NSDictionary<NSDate *, NSArray<NSDateInterval *> *> *sleepByDay, NSError *error) {
|
|
480
|
+
if (isDay) {
|
|
481
|
+
NSArray<NSDateInterval *> *sleep = sleepByDay[range.startDate];
|
|
482
|
+
callback(@[[NSString stringWithFormat:@"DetailedGraph.updateDailySleep(%@,%@)",
|
|
483
|
+
VisitHealthTimestamp(sleep.firstObject.startDate), VisitHealthTimestamp(sleep.lastObject.endDate)]]);
|
|
484
|
+
return;
|
|
485
|
+
}
|
|
486
|
+
NSMutableArray *days = [NSMutableArray new];
|
|
487
|
+
for (NSDate *day = range.startDate; [day compare:lastDay] != NSOrderedDescending;
|
|
488
|
+
day = [graphCalendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:day options:0]) {
|
|
489
|
+
NSArray<NSDateInterval *> *sleep = sleepByDay[day];
|
|
490
|
+
NSInteger weekday = [graphCalendar component:NSCalendarUnitWeekday fromDate:day];
|
|
491
|
+
[days addObject:@{
|
|
492
|
+
@"sleepTime": VisitHealthTimestamp(sleep.firstObject.startDate),
|
|
493
|
+
@"wakeupTime": VisitHealthTimestamp(sleep.lastObject.endDate),
|
|
494
|
+
@"day": graphCalendar.shortWeekdaySymbols[weekday - 1],
|
|
495
|
+
@"startTimestamp": VisitHealthTimestamp(day),
|
|
496
|
+
}];
|
|
497
|
+
}
|
|
498
|
+
NSData *data = [NSJSONSerialization dataWithJSONObject:days options:0 error:nil];
|
|
499
|
+
NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
|
|
500
|
+
callback(@[[NSString stringWithFormat:@"DetailedGraph.updateSleepData(JSON.stringify(%@))", json]]);
|
|
501
|
+
}];
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
if (![@[@"steps", @"calories", @"distance"] containsObject:type ?: @""]) {
|
|
506
|
+
callback(@[]);
|
|
507
|
+
return;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
dispatch_group_t group = dispatch_group_create();
|
|
511
|
+
__block NSArray<NSNumber *> *values = @[];
|
|
512
|
+
__block NSString *activity = @"0";
|
|
513
|
+
dispatch_group_enter(group);
|
|
514
|
+
[self fetchFitnessBuckets:type start:range.startDate end:end hourly:isDay
|
|
515
|
+
completion:^(NSArray<NSNumber *> *result, NSError *error) {
|
|
516
|
+
if (error) NSLog(@"HealthKit %@ graph query failed: %@", type, error.localizedDescription);
|
|
517
|
+
values = result;
|
|
518
|
+
dispatch_group_leave(group);
|
|
519
|
+
}];
|
|
520
|
+
dispatch_group_enter(group);
|
|
521
|
+
[self getActivityTime:date frequency:frequency days:0 callback:^(NSMutableArray *result) {
|
|
522
|
+
activity = result.firstObject ?: @"0";
|
|
523
|
+
dispatch_group_leave(group);
|
|
524
|
+
}];
|
|
525
|
+
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
|
|
526
|
+
NSInteger count = isDay ? 24 : (isWeek ? 7 : 31);
|
|
527
|
+
NSMutableArray *labels = [NSMutableArray new];
|
|
528
|
+
NSMutableArray *buckets = [NSMutableArray new];
|
|
529
|
+
for (NSInteger index = 0; index < count; index++) {
|
|
530
|
+
[labels addObject:@(index + 1)];
|
|
531
|
+
[buckets addObject:index < values.count ? @(values[index].integerValue) : @0];
|
|
532
|
+
}
|
|
533
|
+
callback(@[[NSString stringWithFormat:@"DetailedGraph.updateData([%@],[%@],'%@','%@','%@')",
|
|
534
|
+
[labels componentsJoinedByString:@","], [buckets componentsJoinedByString:@","], type, frequency, activity]]);
|
|
535
|
+
});
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
- (NSDate *)convertStringToDate:(NSString *)date {
|
|
539
|
+
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
|
|
540
|
+
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
|
|
541
|
+
NSLocale *posix = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
|
|
542
|
+
[formatter setLocale:posix];
|
|
543
|
+
return [formatter dateFromString:date];
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
-(void) getDateRanges:(NSDate*) startDate callback:(void(^)(NSMutableArray*))callback{
|
|
547
|
+
NSCalendar *calendar = [NSCalendar currentCalendar];
|
|
548
|
+
dispatch_group_t loadDetailsGroup=dispatch_group_create();
|
|
549
|
+
NSDate *startOfToday = [[NSCalendar calendarWithIdentifier:NSCalendarIdentifierISO8601] startOfDayForDate:[NSDate date]];
|
|
550
|
+
NSDate *startOfNextDay = [[NSCalendar calendarWithIdentifier:NSCalendarIdentifierISO8601] dateByAddingUnit:NSCalendarUnitDay value:1 toDate:startOfToday options:0];
|
|
551
|
+
NSDate *endOfToday = [[NSCalendar calendarWithIdentifier:NSCalendarIdentifierISO8601] dateByAddingUnit:NSCalendarUnitSecond value:-1 toDate:startOfNextDay options:0];
|
|
552
|
+
NSDateComponents *days = [[NSDateComponents alloc] init];
|
|
553
|
+
NSInteger dayCount = 0;
|
|
554
|
+
NSMutableArray *dates=[NSMutableArray new];
|
|
555
|
+
NSDate* startingDate = startDate;
|
|
556
|
+
NSDateComponents *component = [calendar components:NSCalendarUnitDay
|
|
557
|
+
fromDate:startingDate
|
|
558
|
+
toDate:endOfToday
|
|
559
|
+
options:0];
|
|
560
|
+
|
|
561
|
+
NSInteger numberOfDays =[component day];
|
|
562
|
+
if(numberOfDays>30){
|
|
563
|
+
[component setDay:-30];
|
|
564
|
+
startingDate =[calendar dateByAddingComponents:component toDate:endOfToday options:0];
|
|
565
|
+
numberOfDays=30;
|
|
566
|
+
}else{
|
|
567
|
+
[component setDay:-numberOfDays-1];
|
|
568
|
+
startingDate =[calendar dateByAddingComponents:component toDate:endOfToday options:0];
|
|
569
|
+
}
|
|
570
|
+
NSLog(@"numberOfDays are ,%ld, while startingDate is,%@",(long)numberOfDays,startDate);
|
|
571
|
+
|
|
572
|
+
for (NSInteger i=numberOfDays; i>0; i--) {
|
|
573
|
+
dispatch_group_enter(loadDetailsGroup);
|
|
574
|
+
[days setDay: ++dayCount];
|
|
575
|
+
NSDate *date = [calendar dateByAddingComponents: days toDate: startingDate options: 0];
|
|
576
|
+
[dates addObject:date];
|
|
577
|
+
dispatch_group_leave(loadDetailsGroup);
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
dispatch_group_notify(loadDetailsGroup,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^{
|
|
581
|
+
NSLog(@"dispatch_group_notify called %@",dates);
|
|
582
|
+
callback(dates);
|
|
583
|
+
});
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
- (NSDictionary *)hourlySyncPayloadForDate:(NSDate *)date
|
|
587
|
+
steps:(NSArray<NSNumber *> *)steps
|
|
588
|
+
calories:(NSArray<NSNumber *> *)calories
|
|
589
|
+
distance:(NSArray<NSNumber *> *)distance {
|
|
590
|
+
NSMutableArray *records = [NSMutableArray new];
|
|
591
|
+
for (NSInteger hour = 0; hour < steps.count; hour++) {
|
|
592
|
+
[records addObject:@{
|
|
593
|
+
@"st": @(steps[hour].integerValue),
|
|
594
|
+
@"c": @(calories[hour].integerValue),
|
|
595
|
+
@"d": @(distance[hour].integerValue),
|
|
596
|
+
@"h": @(hour),
|
|
597
|
+
@"s": @"",
|
|
598
|
+
}];
|
|
599
|
+
}
|
|
600
|
+
return @{@"data": records, @"dt": VisitHealthTimestamp(date)};
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
- (void)callSyncData:(NSInteger)days dates:(NSArray<NSDate *> *)dates callback:(void (^)(NSArray *))callback {
|
|
604
|
+
if (dates.count == 0) {
|
|
605
|
+
callback(@[]);
|
|
606
|
+
return;
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
NSCalendar *syncCalendar = self->calendar;
|
|
610
|
+
NSDate *firstDay = [syncCalendar startOfDayForDate:dates.firstObject];
|
|
611
|
+
NSDate *lastDay = [syncCalendar startOfDayForDate:dates.lastObject];
|
|
612
|
+
NSDate *nextDay = [syncCalendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:lastDay options:0];
|
|
613
|
+
NSDate *end = [nextDay dateByAddingTimeInterval:-1];
|
|
614
|
+
NSMutableDictionary<NSString *, NSArray<NSNumber *> *> *series = [NSMutableDictionary new];
|
|
615
|
+
__block NSDictionary<NSDate *, NSArray<NSDateInterval *> *> *sleepByDay;
|
|
616
|
+
__block NSArray<NSDictionary *> *activity;
|
|
617
|
+
dispatch_group_t group = dispatch_group_create();
|
|
618
|
+
|
|
619
|
+
for (NSString *metric in @[@"steps", @"calories", @"distance"]) {
|
|
620
|
+
dispatch_group_enter(group);
|
|
621
|
+
[self fetchFitnessBuckets:metric start:firstDay end:end hourly:NO
|
|
622
|
+
completion:^(NSArray<NSNumber *> *values, NSError *error) {
|
|
623
|
+
if (error) NSLog(@"HealthKit %@ sync query failed: %@", metric, error.localizedDescription);
|
|
624
|
+
@synchronized (series) { if (!error) series[metric] = values; }
|
|
625
|
+
dispatch_group_leave(group);
|
|
626
|
+
}];
|
|
627
|
+
}
|
|
628
|
+
dispatch_group_enter(group);
|
|
629
|
+
[self fetchSleepFromDay:firstDay throughDay:lastDay
|
|
630
|
+
completion:^(NSDictionary<NSDate *, NSArray<NSDateInterval *> *> *sleep, NSError *error) {
|
|
631
|
+
if (error) NSLog(@"HealthKit sleep sync query failed: %@", error.localizedDescription);
|
|
632
|
+
if (!error) sleepByDay = sleep;
|
|
633
|
+
dispatch_group_leave(group);
|
|
634
|
+
}];
|
|
635
|
+
dispatch_group_enter(group);
|
|
636
|
+
[self getActivityTime:end frequency:@"custom" days:days callback:^(NSArray *result) {
|
|
637
|
+
activity = result.count > 1 ? result[1] : @[];
|
|
638
|
+
dispatch_group_leave(group);
|
|
639
|
+
}];
|
|
640
|
+
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
|
|
641
|
+
if (series.count != 3 || !sleepByDay) {
|
|
642
|
+
callback(@[]);
|
|
643
|
+
return;
|
|
644
|
+
}
|
|
645
|
+
NSMutableDictionary<NSDate *, NSNumber *> *activityByDay = [NSMutableDictionary new];
|
|
646
|
+
for (NSDictionary *value in activity) {
|
|
647
|
+
activityByDay[[syncCalendar startOfDayForDate:value[@"date"]]] = value[@"value"];
|
|
648
|
+
}
|
|
649
|
+
NSMutableArray *fitnessData = [NSMutableArray new];
|
|
650
|
+
for (NSDate *date in dates) {
|
|
651
|
+
NSDate *day = [syncCalendar startOfDayForDate:date];
|
|
652
|
+
NSInteger index = [syncCalendar components:NSCalendarUnitDay fromDate:firstDay toDate:day options:0].day;
|
|
653
|
+
NSMutableDictionary *record = [@{@"date": VisitHealthTimestamp(date)} mutableCopy];
|
|
654
|
+
for (NSString *metric in @[@"steps", @"calories", @"distance"]) {
|
|
655
|
+
NSArray<NSNumber *> *values = series[metric];
|
|
656
|
+
record[metric] = index >= 0 && index < values.count ? values[index] : @0;
|
|
657
|
+
}
|
|
658
|
+
NSNumber *duration = activityByDay[day];
|
|
659
|
+
if (duration) record[@"activity"] = duration;
|
|
660
|
+
NSArray<NSDateInterval *> *sleep = sleepByDay[day];
|
|
661
|
+
if (sleep.count > 0) {
|
|
662
|
+
record[@"sleep"] = [NSString stringWithFormat:@"%@-%@",
|
|
663
|
+
VisitHealthTimestamp(sleep.firstObject.startDate), VisitHealthTimestamp(sleep.lastObject.endDate)];
|
|
664
|
+
}
|
|
665
|
+
[fitnessData addObject:record];
|
|
666
|
+
}
|
|
667
|
+
callback(@[@{@"fitnessData": fitnessData}]);
|
|
668
|
+
});
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
RCT_EXPORT_METHOD(connectToAppleHealth:(RCTResponseSenderBlock)callback)
|
|
672
|
+
{
|
|
673
|
+
if (![HKHealthStore isHealthDataAvailable]) {
|
|
674
|
+
callback(@[@{@"authStatus": @"UNAVAILABLE"}]);
|
|
675
|
+
return;
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
NSSet *readTypes = [self fitnessReadTypes];
|
|
679
|
+
|
|
680
|
+
__weak typeof(self) weakSelf = self;
|
|
681
|
+
|
|
682
|
+
void (^finish)(void) = ^{
|
|
683
|
+
__strong typeof(weakSelf) strongSelf = weakSelf;
|
|
684
|
+
if (!strongSelf) { return; }
|
|
685
|
+
|
|
686
|
+
[strongSelf hasReadableFitnessSamples:^(BOOL readable) {
|
|
687
|
+
if (!readable) {
|
|
688
|
+
dispatch_async(dispatch_get_main_queue(), ^{
|
|
689
|
+
callback(@[@{@"authStatus": @"DENIED"}]);
|
|
690
|
+
});
|
|
691
|
+
return;
|
|
692
|
+
}
|
|
693
|
+
[strongSelf onHealthKitPermissionGranted:^(NSDictionary *data) {
|
|
694
|
+
NSMutableDictionary *out =
|
|
695
|
+
[NSMutableDictionary dictionaryWithDictionary:data ?: @{}];
|
|
696
|
+
out[@"authStatus"] = @"GRANTED";
|
|
697
|
+
dispatch_async(dispatch_get_main_queue(), ^{
|
|
698
|
+
callback(@[out]);
|
|
699
|
+
});
|
|
700
|
+
}];
|
|
701
|
+
}];
|
|
702
|
+
};
|
|
703
|
+
|
|
704
|
+
[self healthKitRequestStatus:^(HKAuthorizationRequestStatus status) {
|
|
705
|
+
if (status == HKAuthorizationRequestStatusUnnecessary) {
|
|
706
|
+
finish();
|
|
707
|
+
return;
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
[[VisitRnSdkViewManager sharedManager]
|
|
711
|
+
requestAuthorizationToShareTypes:nil
|
|
712
|
+
readTypes:readTypes
|
|
713
|
+
completion:^(BOOL success, NSError *error) {
|
|
714
|
+
if (!success) {
|
|
715
|
+
NSLog(@"connectToAppleHealth authorization failed: %@", error.localizedDescription);
|
|
716
|
+
dispatch_async(dispatch_get_main_queue(), ^{
|
|
717
|
+
callback(@[@{@"authStatus": @"DENIED"}]);
|
|
718
|
+
});
|
|
719
|
+
return;
|
|
720
|
+
}
|
|
721
|
+
finish();
|
|
722
|
+
}];
|
|
723
|
+
}];
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
// Opens Settings.app on the Health section (Settings → Health → Data Access
|
|
727
|
+
// & Devices path). Uses the unofficial `App-Prefs:root=HEALTH` URL scheme
|
|
728
|
+
// with a graceful fallback to `UIApplicationOpenSettingsURLString` (the
|
|
729
|
+
// current app's Settings page) if iOS refuses the deep link. Vendors should
|
|
730
|
+
// note the App Review caveat around `App-Prefs:` schemes documented in the
|
|
731
|
+
// iOS vendor guide.
|
|
732
|
+
RCT_EXPORT_METHOD(openAppleHealthApp:(RCTPromiseResolveBlock)resolve
|
|
733
|
+
rejecter:(RCTPromiseRejectBlock)reject)
|
|
734
|
+
{
|
|
735
|
+
dispatch_async(dispatch_get_main_queue(), ^{
|
|
736
|
+
UIApplication *app = [UIApplication sharedApplication];
|
|
737
|
+
|
|
738
|
+
void (^openAppSettings)(void) = ^{
|
|
739
|
+
NSURL *settingsUrl = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
|
|
740
|
+
if (!settingsUrl) {
|
|
741
|
+
reject(@"OPEN_HEALTH_FAILED", @"Settings URL is unavailable", nil);
|
|
742
|
+
return;
|
|
743
|
+
}
|
|
744
|
+
[app openURL:settingsUrl options:@{} completionHandler:^(BOOL success) {
|
|
745
|
+
if (success) {
|
|
746
|
+
resolve(@YES);
|
|
747
|
+
} else {
|
|
748
|
+
reject(@"OPEN_HEALTH_FAILED", @"Unable to open Settings app", nil);
|
|
749
|
+
}
|
|
750
|
+
}];
|
|
751
|
+
};
|
|
752
|
+
|
|
753
|
+
NSURL *healthPrefsUrl = [NSURL URLWithString:@"App-Prefs:root=HEALTH"];
|
|
754
|
+
if (!healthPrefsUrl) {
|
|
755
|
+
openAppSettings();
|
|
756
|
+
return;
|
|
757
|
+
}
|
|
758
|
+
[app openURL:healthPrefsUrl options:@{} completionHandler:^(BOOL success) {
|
|
759
|
+
if (success) {
|
|
760
|
+
resolve(@YES);
|
|
761
|
+
} else {
|
|
762
|
+
openAppSettings();
|
|
763
|
+
}
|
|
764
|
+
}];
|
|
765
|
+
});
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
RCT_EXPORT_METHOD(renderGraph:(NSDictionary *)input callback:(RCTResponseSenderBlock)callback)
|
|
769
|
+
{
|
|
770
|
+
NSString *type = [input objectForKey:@"type"];
|
|
771
|
+
NSString *frequency = [input objectForKey:@"frequency"];
|
|
772
|
+
NSString *timestamp = [input objectForKey:@"timestamp"];
|
|
773
|
+
NSDate *date = [NSDate dateWithTimeIntervalSince1970:[timestamp doubleValue]/1000];
|
|
774
|
+
[self renderGraphData:type frequency:frequency date:date callback:^(NSArray * data) {
|
|
775
|
+
NSLog(@"renderGraphData data is, %@",data);
|
|
776
|
+
callback(@[[NSNull null], data]);
|
|
777
|
+
}];
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
- (void)postJSONBody:(NSDictionary *)body
|
|
781
|
+
toURL:(NSString *)urlString
|
|
782
|
+
authToken:(NSString *)authToken
|
|
783
|
+
completion:(void (^)(NSError *error, NSInteger status))completion
|
|
784
|
+
{
|
|
785
|
+
NSURL *url = [NSURL URLWithString:urlString];
|
|
786
|
+
if (!url) {
|
|
787
|
+
completion([NSError errorWithDomain:@"VisitSync" code:-1
|
|
788
|
+
userInfo:@{NSLocalizedDescriptionKey:
|
|
789
|
+
[NSString stringWithFormat:@"Invalid URL: %@", urlString]}],
|
|
790
|
+
0);
|
|
791
|
+
return;
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
NSError *jsonError = nil;
|
|
795
|
+
NSData *bodyData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&jsonError];
|
|
796
|
+
if (jsonError) {
|
|
797
|
+
completion(jsonError, 0);
|
|
798
|
+
return;
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
|
|
802
|
+
request.HTTPMethod = @"POST";
|
|
803
|
+
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
|
|
804
|
+
if (authToken.length > 0) {
|
|
805
|
+
[request setValue:authToken forHTTPHeaderField:@"Authorization"];
|
|
806
|
+
}
|
|
807
|
+
request.HTTPBody = bodyData;
|
|
808
|
+
|
|
809
|
+
NSURLSessionDataTask *task =
|
|
810
|
+
[[NSURLSession sharedSession] dataTaskWithRequest:request
|
|
811
|
+
completionHandler:^(NSData *data,
|
|
812
|
+
NSURLResponse *response,
|
|
813
|
+
NSError *error) {
|
|
814
|
+
NSInteger status = 0;
|
|
815
|
+
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
|
|
816
|
+
status = ((NSHTTPURLResponse *)response).statusCode;
|
|
817
|
+
}
|
|
818
|
+
completion(error, status);
|
|
819
|
+
}];
|
|
820
|
+
[task resume];
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
- (void)collectEmbellishBatchesForDates:(NSArray<NSDate *> *)dates
|
|
824
|
+
completion:(void (^)(NSArray<NSDictionary *> *))completion {
|
|
825
|
+
dispatch_group_t group = dispatch_group_create();
|
|
826
|
+
NSMutableDictionary<NSDate *, NSDictionary *> *batches = [NSMutableDictionary new];
|
|
827
|
+
for (NSDate *date in dates) {
|
|
828
|
+
dispatch_group_enter(group);
|
|
829
|
+
[self fetchHourlyFitnessForDate:date completion:^(NSArray<NSNumber *> *steps,
|
|
830
|
+
NSArray<NSNumber *> *calories,
|
|
831
|
+
NSArray<NSNumber *> *distance) {
|
|
832
|
+
if (steps && calories && distance) {
|
|
833
|
+
batches[date] = [self hourlySyncPayloadForDate:date steps:steps calories:calories distance:distance];
|
|
834
|
+
}
|
|
835
|
+
dispatch_group_leave(group);
|
|
836
|
+
}];
|
|
837
|
+
}
|
|
838
|
+
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
|
|
839
|
+
NSMutableArray *ordered = [NSMutableArray new];
|
|
840
|
+
for (NSDate *date in dates) {
|
|
841
|
+
NSDictionary *batch = batches[date];
|
|
842
|
+
if (batch) [ordered addObject:batch];
|
|
843
|
+
}
|
|
844
|
+
completion(ordered);
|
|
845
|
+
});
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
// Shared sync executor. Called from updateApiUrl (fire-and-forget) and
|
|
849
|
+
// triggerManualSync (promise). Handles date-range → collection → HTTP POST for
|
|
850
|
+
// both the embellish (hourly) and data-sync (daily) endpoints.
|
|
851
|
+
- (void)performVisitSyncWithBaseUrl:(NSString *)baseUrl
|
|
852
|
+
authToken:(NSString *)authToken
|
|
853
|
+
hourlySince:(NSTimeInterval)gfHourlyLastSync
|
|
854
|
+
dailySince:(NSTimeInterval)googleFitLastSync
|
|
855
|
+
resolve:(RCTPromiseResolveBlock)resolve
|
|
856
|
+
reject:(RCTPromiseRejectBlock)reject
|
|
857
|
+
{
|
|
858
|
+
NSDate *hourlyDataSyncTime = [NSDate dateWithTimeIntervalSince1970:gfHourlyLastSync / 1000];
|
|
859
|
+
NSDate *dailyDataSyncTime = [NSDate dateWithTimeIntervalSince1970:googleFitLastSync / 1000];
|
|
860
|
+
|
|
861
|
+
NSString *embellishUrl = [NSString stringWithFormat:@"%@/users/embellish-sync", baseUrl];
|
|
862
|
+
NSString *dataSyncUrl = [NSString stringWithFormat:@"%@/users/data-sync", baseUrl];
|
|
863
|
+
|
|
864
|
+
__block NSError *firstError = nil;
|
|
865
|
+
NSLock *errorLock = [[NSLock alloc] init];
|
|
866
|
+
void (^recordError)(NSError *) = ^(NSError *err) {
|
|
867
|
+
if (!err) { return; }
|
|
868
|
+
[errorLock lock];
|
|
869
|
+
if (!firstError) { firstError = err; }
|
|
870
|
+
[errorLock unlock];
|
|
871
|
+
};
|
|
872
|
+
|
|
873
|
+
dispatch_group_t topGroup = dispatch_group_create();
|
|
874
|
+
__weak typeof(self) weakSelf = self;
|
|
875
|
+
|
|
876
|
+
// Hourly / embellish flow
|
|
877
|
+
dispatch_group_enter(topGroup);
|
|
878
|
+
[self getDateRanges:hourlyDataSyncTime callback:^(NSMutableArray *dates) {
|
|
879
|
+
__strong typeof(weakSelf) strongSelf = weakSelf;
|
|
880
|
+
if (!strongSelf) {
|
|
881
|
+
dispatch_group_leave(topGroup);
|
|
882
|
+
return;
|
|
883
|
+
}
|
|
884
|
+
[strongSelf collectEmbellishBatchesForDates:dates
|
|
885
|
+
completion:^(NSArray *batches) {
|
|
886
|
+
if (batches.count == 0) {
|
|
887
|
+
NSLog(@"[Visit Sync] no embellish batches to POST");
|
|
888
|
+
dispatch_group_leave(topGroup);
|
|
889
|
+
return;
|
|
890
|
+
}
|
|
891
|
+
dispatch_group_t postGroup = dispatch_group_create();
|
|
892
|
+
for (NSDictionary *body in batches) {
|
|
893
|
+
dispatch_group_enter(postGroup);
|
|
894
|
+
[strongSelf postJSONBody:body
|
|
895
|
+
toURL:embellishUrl
|
|
896
|
+
authToken:authToken
|
|
897
|
+
completion:^(NSError *err, NSInteger status) {
|
|
898
|
+
NSLog(@"[Visit Sync] embellish POST status=%ld err=%@",
|
|
899
|
+
(long)status, err.localizedDescription);
|
|
900
|
+
if (err) {
|
|
901
|
+
recordError(err);
|
|
902
|
+
} else if (status < 200 || status >= 300) {
|
|
903
|
+
recordError([NSError errorWithDomain:@"VisitSync"
|
|
904
|
+
code:status
|
|
905
|
+
userInfo:@{NSLocalizedDescriptionKey:
|
|
906
|
+
[NSString stringWithFormat:
|
|
907
|
+
@"embellish HTTP %ld",
|
|
908
|
+
(long)status]}]);
|
|
909
|
+
}
|
|
910
|
+
dispatch_group_leave(postGroup);
|
|
911
|
+
}];
|
|
912
|
+
}
|
|
913
|
+
dispatch_group_notify(postGroup,
|
|
914
|
+
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
|
|
915
|
+
dispatch_group_leave(topGroup);
|
|
916
|
+
});
|
|
917
|
+
}];
|
|
918
|
+
}];
|
|
919
|
+
|
|
920
|
+
// Daily / data-sync flow
|
|
921
|
+
dispatch_group_enter(topGroup);
|
|
922
|
+
[self getDateRanges:dailyDataSyncTime callback:^(NSMutableArray *dates) {
|
|
923
|
+
__strong typeof(weakSelf) strongSelf = weakSelf;
|
|
924
|
+
if (!strongSelf || dates.count == 0) {
|
|
925
|
+
dispatch_group_leave(topGroup);
|
|
926
|
+
return;
|
|
927
|
+
}
|
|
928
|
+
[strongSelf callSyncData:dates.count
|
|
929
|
+
dates:dates
|
|
930
|
+
callback:^(NSArray *data) {
|
|
931
|
+
if (data.count == 0 || ![data[0] isKindOfClass:[NSDictionary class]]) {
|
|
932
|
+
NSLog(@"[Visit Sync] no daily sync payload to POST");
|
|
933
|
+
dispatch_group_leave(topGroup);
|
|
934
|
+
return;
|
|
935
|
+
}
|
|
936
|
+
[strongSelf postJSONBody:data[0]
|
|
937
|
+
toURL:dataSyncUrl
|
|
938
|
+
authToken:authToken
|
|
939
|
+
completion:^(NSError *err, NSInteger status) {
|
|
940
|
+
NSLog(@"[Visit Sync] data-sync POST status=%ld err=%@",
|
|
941
|
+
(long)status, err.localizedDescription);
|
|
942
|
+
if (err) {
|
|
943
|
+
recordError(err);
|
|
944
|
+
} else if (status < 200 || status >= 300) {
|
|
945
|
+
recordError([NSError errorWithDomain:@"VisitSync"
|
|
946
|
+
code:status
|
|
947
|
+
userInfo:@{NSLocalizedDescriptionKey:
|
|
948
|
+
[NSString stringWithFormat:
|
|
949
|
+
@"data-sync HTTP %ld",
|
|
950
|
+
(long)status]}]);
|
|
951
|
+
}
|
|
952
|
+
dispatch_group_leave(topGroup);
|
|
953
|
+
}];
|
|
954
|
+
}];
|
|
955
|
+
}];
|
|
956
|
+
|
|
957
|
+
dispatch_group_notify(topGroup, dispatch_get_main_queue(), ^{
|
|
958
|
+
self.isSyncInProgress = NO;
|
|
959
|
+
if (firstError) {
|
|
960
|
+
if (reject) {
|
|
961
|
+
reject(@"SYNC_FAILED",
|
|
962
|
+
firstError.localizedDescription ?: @"Sync failed",
|
|
963
|
+
firstError);
|
|
964
|
+
}
|
|
965
|
+
} else {
|
|
966
|
+
if (resolve) {
|
|
967
|
+
resolve(@"Health Data Sync Completed");
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
});
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
RCT_EXPORT_METHOD(updateApiUrl:(NSDictionary *)input)
|
|
974
|
+
{
|
|
975
|
+
NSString *apiBaseUrl = [input objectForKey:@"apiBaseUrl"];
|
|
976
|
+
NSString *authToken = [input objectForKey:@"authToken"];
|
|
977
|
+
NSTimeInterval gfHourlyLastSync = [[input objectForKey:@"gfHourlyLastSync"] doubleValue];
|
|
978
|
+
NSTimeInterval googleFitLastSync = [[input objectForKey:@"googleFitLastSync"] doubleValue];
|
|
979
|
+
|
|
980
|
+
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
|
|
981
|
+
if (apiBaseUrl.length > 0) {
|
|
982
|
+
[defaults setObject:apiBaseUrl forKey:kVisitApiBaseUrlKey];
|
|
983
|
+
}
|
|
984
|
+
if (authToken.length > 0) {
|
|
985
|
+
[defaults setObject:authToken forKey:kVisitAuthTokenKey];
|
|
986
|
+
}
|
|
987
|
+
if (gfHourlyLastSync > 0) {
|
|
988
|
+
[defaults setDouble:gfHourlyLastSync forKey:kVisitHourlyLastSyncKey];
|
|
989
|
+
}
|
|
990
|
+
if (googleFitLastSync > 0) {
|
|
991
|
+
[defaults setDouble:googleFitLastSync forKey:kVisitDailyLastSyncKey];
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
NSString *storedBaseUrl = apiBaseUrl.length > 0 ? apiBaseUrl : [defaults stringForKey:kVisitApiBaseUrlKey];
|
|
995
|
+
NSString *storedAuthToken = authToken.length > 0 ? authToken : [defaults stringForKey:kVisitAuthTokenKey];
|
|
996
|
+
|
|
997
|
+
if (![HKHealthStore isHealthDataAvailable]) {
|
|
998
|
+
return;
|
|
999
|
+
}
|
|
1000
|
+
if (storedBaseUrl.length == 0 || storedAuthToken.length == 0) {
|
|
1001
|
+
return;
|
|
1002
|
+
}
|
|
1003
|
+
if (self.isSyncInProgress) {
|
|
1004
|
+
return;
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
self.isSyncInProgress = YES;
|
|
1008
|
+
__weak typeof(self) weakSelf = self;
|
|
1009
|
+
[self canAccessHealthKit:^(BOOL value) {
|
|
1010
|
+
__strong typeof(weakSelf) strongSelf = weakSelf;
|
|
1011
|
+
if (!strongSelf) { return; }
|
|
1012
|
+
if (!value) {
|
|
1013
|
+
strongSelf.isSyncInProgress = NO;
|
|
1014
|
+
[strongSelf requestAuthorization:^(NSDictionary *data) { (void)data; }];
|
|
1015
|
+
return;
|
|
1016
|
+
}
|
|
1017
|
+
[strongSelf performVisitSyncWithBaseUrl:storedBaseUrl
|
|
1018
|
+
authToken:storedAuthToken
|
|
1019
|
+
hourlySince:gfHourlyLastSync
|
|
1020
|
+
dailySince:googleFitLastSync
|
|
1021
|
+
resolve:nil
|
|
1022
|
+
reject:nil];
|
|
1023
|
+
}];
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
|
|
1027
|
+
RCT_EXPORT_METHOD(fetchHourlyData:(NSInteger)gfHourlyLastSync resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) {
|
|
1028
|
+
NSDate *date = [NSDate dateWithTimeIntervalSince1970:gfHourlyLastSync / 1000.0];
|
|
1029
|
+
[self canAccessHealthKit:^(BOOL readable) {
|
|
1030
|
+
if (!readable) {
|
|
1031
|
+
reject(@"error", @"Error fetching hourly data", nil);
|
|
1032
|
+
return;
|
|
1033
|
+
}
|
|
1034
|
+
[self collectEmbellishBatchesForDates:@[date] completion:^(NSArray *batches) {
|
|
1035
|
+
resolve(batches);
|
|
1036
|
+
}];
|
|
1037
|
+
}];
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
RCT_EXPORT_METHOD(fetchDailyData:(NSInteger)googleFitLastSync resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){
|
|
1041
|
+
NSLog(@"gfHourlyLastSync in fetchHourlyData is %ld",(long)googleFitLastSync);
|
|
1042
|
+
NSDate* dailyDataSyncTime = [NSDate dateWithTimeIntervalSince1970:googleFitLastSync/1000];
|
|
1043
|
+
[self canAccessHealthKit:^(BOOL value){
|
|
1044
|
+
if(value){
|
|
1045
|
+
[self getDateRanges:dailyDataSyncTime callback:^(NSMutableArray * dates) {
|
|
1046
|
+
if([dates count]>0){
|
|
1047
|
+
[self callSyncData:[dates count] dates:dates callback:^(NSArray * data) {
|
|
1048
|
+
NSLog(@"fetchDailyData data is, %@",data);
|
|
1049
|
+
resolve(data);
|
|
1050
|
+
}];
|
|
1051
|
+
}
|
|
1052
|
+
}];
|
|
1053
|
+
}else{
|
|
1054
|
+
NSError* error;
|
|
1055
|
+
reject(@"error", @"Error fetching daily data", error);
|
|
1056
|
+
}
|
|
1057
|
+
}];
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
RCT_REMAP_METHOD(getHealthKitConnectStatus,
|
|
1061
|
+
getHealthKitConnectStatusWithResolver:(RCTPromiseResolveBlock)resolve
|
|
1062
|
+
rejecter:(RCTPromiseRejectBlock)reject)
|
|
1063
|
+
{
|
|
1064
|
+
if (![HKHealthStore isHealthDataAvailable]) {
|
|
1065
|
+
resolve(@"NOT_SUPPORTED");
|
|
1066
|
+
return;
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
[self canAccessHealthKit:^(BOOL granted) {
|
|
1070
|
+
dispatch_async(dispatch_get_main_queue(), ^{
|
|
1071
|
+
resolve(granted ? @"CONNECTED" : @"INSTALLED");
|
|
1072
|
+
});
|
|
1073
|
+
}];
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
// HealthKit Authorization Check
|
|
1077
|
+
RCT_REMAP_METHOD(getHealthKitStatus,
|
|
1078
|
+
checkHealthKitAuthorizationWithResolver:(RCTPromiseResolveBlock)resolve
|
|
1079
|
+
rejecter:(RCTPromiseRejectBlock)reject)
|
|
1080
|
+
{
|
|
1081
|
+
if (![HKHealthStore isHealthDataAvailable]) {
|
|
1082
|
+
resolve(@(NO));
|
|
1083
|
+
return;
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
// Was gated on HKAuthorizationStatusSharingAuthorized, i.e. *write*
|
|
1087
|
+
// authorization, which this read-only SDK no longer requests. Now gated on
|
|
1088
|
+
// whether the permission sheet has been answered.
|
|
1089
|
+
[self canAccessHealthKit:^(BOOL resolved) {
|
|
1090
|
+
if (!resolved) {
|
|
1091
|
+
dispatch_async(dispatch_get_main_queue(), ^{
|
|
1092
|
+
resolve(@(NO)); // HealthKit access not granted
|
|
1093
|
+
});
|
|
1094
|
+
return;
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
NSDate *now = [NSDate date];
|
|
1098
|
+
NSDate *today = [self->calendar startOfDayForDate:now];
|
|
1099
|
+
[self fetchFitnessBuckets:@"steps" start:today end:now hourly:NO
|
|
1100
|
+
completion:^(NSArray<NSNumber *> *stepsData, NSError *queryError) {
|
|
1101
|
+
dispatch_async(dispatch_get_main_queue(), ^{
|
|
1102
|
+
if (!queryError) {
|
|
1103
|
+
resolve(@{@"steps": stepsData});
|
|
1104
|
+
} else {
|
|
1105
|
+
reject(@"fetch_error", @"Error fetching step data", queryError);
|
|
1106
|
+
}
|
|
1107
|
+
});
|
|
1108
|
+
}];
|
|
1109
|
+
}];
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
RCT_REMAP_METHOD(requestHealthKitAuthorization,
|
|
1113
|
+
requestHealthKitAuthorizationWithResolver:(RCTPromiseResolveBlock)resolve
|
|
1114
|
+
rejecter:(RCTPromiseRejectBlock)reject)
|
|
1115
|
+
{
|
|
1116
|
+
if (![HKHealthStore isHealthDataAvailable]) {
|
|
1117
|
+
reject(@"HEALTH_DATA_UNAVAILABLE", @"HealthKit is not available on this device", nil);
|
|
1118
|
+
return;
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
NSSet *readTypes = [self fitnessReadTypes];
|
|
1122
|
+
|
|
1123
|
+
__weak typeof(self) weakSelf = self;
|
|
1124
|
+
[[VisitRnSdkViewManager sharedManager]
|
|
1125
|
+
requestAuthorizationToShareTypes:nil
|
|
1126
|
+
readTypes:readTypes
|
|
1127
|
+
completion:^(BOOL success, NSError *error) {
|
|
1128
|
+
__strong typeof(weakSelf) strongSelf = weakSelf;
|
|
1129
|
+
if (!success || !strongSelf) {
|
|
1130
|
+
dispatch_async(dispatch_get_main_queue(), ^{
|
|
1131
|
+
reject(@"AUTHORIZATION_FAILED",
|
|
1132
|
+
error.localizedDescription ?: @"HealthKit authorization failed",
|
|
1133
|
+
error);
|
|
1134
|
+
});
|
|
1135
|
+
return;
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
// HealthKit exposes readable samples rather than per-type read authorization.
|
|
1139
|
+
[strongSelf canAccessHealthKit:^(BOOL resolved) {
|
|
1140
|
+
dispatch_async(dispatch_get_main_queue(), ^{
|
|
1141
|
+
resolve(resolved ? @"GRANTED" : @"NOT_DETERMINED");
|
|
1142
|
+
});
|
|
1143
|
+
}];
|
|
1144
|
+
}];
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1147
|
+
RCT_REMAP_METHOD(getTodayStepCount,
|
|
1148
|
+
getTodayStepCountWithResolver:(RCTPromiseResolveBlock)resolve
|
|
1149
|
+
rejecter:(RCTPromiseRejectBlock)reject)
|
|
1150
|
+
{
|
|
1151
|
+
if (![HKHealthStore isHealthDataAvailable]) {
|
|
1152
|
+
reject(@"HEALTH_DATA_UNAVAILABLE", @"HealthKit is not available on this device", nil);
|
|
1153
|
+
return;
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
NSCalendar *cal = [NSCalendar currentCalendar];
|
|
1157
|
+
NSDate *startOfDay = [cal startOfDayForDate:[NSDate date]];
|
|
1158
|
+
NSDateComponents *dayInterval = [[NSDateComponents alloc] init];
|
|
1159
|
+
dayInterval.day = 1;
|
|
1160
|
+
|
|
1161
|
+
HKQuantityType *stepType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
|
|
1162
|
+
|
|
1163
|
+
HKStatisticsCollectionQuery *query = [[HKStatisticsCollectionQuery alloc]
|
|
1164
|
+
initWithQuantityType:stepType
|
|
1165
|
+
quantitySamplePredicate:nil
|
|
1166
|
+
options:HKStatisticsOptionCumulativeSum
|
|
1167
|
+
anchorDate:startOfDay
|
|
1168
|
+
intervalComponents:dayInterval];
|
|
1169
|
+
|
|
1170
|
+
query.initialResultsHandler = ^(HKStatisticsCollectionQuery *q,
|
|
1171
|
+
HKStatisticsCollection *collection,
|
|
1172
|
+
NSError *error) {
|
|
1173
|
+
if (error) {
|
|
1174
|
+
reject(@"STEP_QUERY_FAILED",
|
|
1175
|
+
error.localizedDescription ?: @"Failed to query step count",
|
|
1176
|
+
error);
|
|
1177
|
+
return;
|
|
1178
|
+
}
|
|
1179
|
+
HKStatistics *todayStats = [collection statisticsForDate:startOfDay];
|
|
1180
|
+
HKQuantity *sum = todayStats.sumQuantity;
|
|
1181
|
+
NSInteger steps = sum ? (NSInteger)[sum doubleValueForUnit:[HKUnit countUnit]] : 0;
|
|
1182
|
+
resolve(@(steps));
|
|
1183
|
+
};
|
|
1184
|
+
|
|
1185
|
+
[[VisitRnSdkViewManager sharedManager] executeQuery:query];
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
RCT_REMAP_METHOD(getTodaySleepMinutes,
|
|
1189
|
+
getTodaySleepMinutesWithResolver:(RCTPromiseResolveBlock)resolve
|
|
1190
|
+
rejecter:(RCTPromiseRejectBlock)reject) {
|
|
1191
|
+
if (![HKHealthStore isHealthDataAvailable]) {
|
|
1192
|
+
reject(@"HEALTH_DATA_UNAVAILABLE", @"HealthKit is not available on this device", nil);
|
|
1193
|
+
return;
|
|
1194
|
+
}
|
|
1195
|
+
[self fetchTodaySleepMinutes:^(NSNumber *minutes, NSError *error) {
|
|
1196
|
+
if (error) {
|
|
1197
|
+
reject(@"SLEEP_QUERY_FAILED", error.localizedDescription, error);
|
|
1198
|
+
} else {
|
|
1199
|
+
resolve(minutes);
|
|
1200
|
+
}
|
|
1201
|
+
}];
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
RCT_REMAP_METHOD(getTodayCalorieCount,
|
|
1205
|
+
getTodayCalorieCountWithResolver:(RCTPromiseResolveBlock)resolve
|
|
1206
|
+
rejecter:(RCTPromiseRejectBlock)reject) {
|
|
1207
|
+
if (![HKHealthStore isHealthDataAvailable]) {
|
|
1208
|
+
reject(@"HEALTH_DATA_UNAVAILABLE", @"HealthKit is not available on this device", nil);
|
|
1209
|
+
return;
|
|
1210
|
+
}
|
|
1211
|
+
NSDate *now = [NSDate date];
|
|
1212
|
+
NSDate *today = [self->calendar startOfDayForDate:now];
|
|
1213
|
+
[self fetchFitnessBuckets:@"calories" start:today end:now hourly:NO
|
|
1214
|
+
completion:^(NSArray<NSNumber *> *values, NSError *error) {
|
|
1215
|
+
if (error) {
|
|
1216
|
+
reject(@"CALORIE_QUERY_FAILED", error.localizedDescription, error);
|
|
1217
|
+
} else {
|
|
1218
|
+
resolve(values.firstObject ?: @0);
|
|
1219
|
+
}
|
|
1220
|
+
}];
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
RCT_REMAP_METHOD(triggerManualSync,
|
|
1224
|
+
triggerManualSyncWithResolver:(RCTPromiseResolveBlock)resolve
|
|
1225
|
+
rejecter:(RCTPromiseRejectBlock)reject)
|
|
1226
|
+
{
|
|
1227
|
+
if (![HKHealthStore isHealthDataAvailable]) {
|
|
1228
|
+
reject(@"HEALTH_DATA_UNAVAILABLE", @"HealthKit is not available on this device", nil);
|
|
1229
|
+
return;
|
|
1230
|
+
}
|
|
1231
|
+
if (self.isSyncInProgress) {
|
|
1232
|
+
reject(@"SYNC_IN_PROGRESS", @"Health data sync is already in progress", nil);
|
|
1233
|
+
return;
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1236
|
+
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
|
|
1237
|
+
NSString *baseUrl = [defaults stringForKey:kVisitApiBaseUrlKey];
|
|
1238
|
+
NSString *authToken = [defaults stringForKey:kVisitAuthTokenKey];
|
|
1239
|
+
NSTimeInterval gfHourlyLastSync = [defaults doubleForKey:kVisitHourlyLastSyncKey];
|
|
1240
|
+
NSTimeInterval googleFitLastSync = [defaults doubleForKey:kVisitDailyLastSyncKey];
|
|
1241
|
+
|
|
1242
|
+
if (baseUrl.length == 0 || authToken.length == 0) {
|
|
1243
|
+
reject(@"MISSING_SYNC_CREDENTIALS",
|
|
1244
|
+
@"Visit apiBaseUrl or authToken is missing. Ensure the WebView has mounted at least once so credentials are seeded.",
|
|
1245
|
+
nil);
|
|
1246
|
+
return;
|
|
1247
|
+
}
|
|
1248
|
+
if (gfHourlyLastSync <= 0 && googleFitLastSync <= 0) {
|
|
1249
|
+
reject(@"MISSING_SYNC_TIMESTAMPS",
|
|
1250
|
+
@"Visit sync timestamps are missing. Ensure the WebView has run at least once.",
|
|
1251
|
+
nil);
|
|
1252
|
+
return;
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
self.isSyncInProgress = YES;
|
|
1256
|
+
__weak typeof(self) weakSelf = self;
|
|
1257
|
+
[self canAccessHealthKit:^(BOOL value) {
|
|
1258
|
+
__strong typeof(weakSelf) strongSelf = weakSelf;
|
|
1259
|
+
if (!strongSelf) { return; }
|
|
1260
|
+
if (!value) {
|
|
1261
|
+
strongSelf.isSyncInProgress = NO;
|
|
1262
|
+
reject(@"PERMISSION_DENIED", @"HealthKit permission is not granted", nil);
|
|
1263
|
+
return;
|
|
1264
|
+
}
|
|
1265
|
+
[strongSelf performVisitSyncWithBaseUrl:baseUrl
|
|
1266
|
+
authToken:authToken
|
|
1267
|
+
hourlySince:gfHourlyLastSync
|
|
1268
|
+
dailySince:googleFitLastSync
|
|
1269
|
+
resolve:resolve
|
|
1270
|
+
reject:reject];
|
|
1271
|
+
}];
|
|
1272
|
+
}
|
|
1273
|
+
|
|
23
1274
|
@end
|