rn-apple-healthkit icon indicating copy to clipboard operation
rn-apple-healthkit copied to clipboard

How to catch authorization error?

Open mifi opened this issue 5 years ago • 4 comments

For example when trying

AppleHealthKit.saveMindfulSession({ startDate: ..., endDate: ... }, (err) => {
  if (err) console.error(err.code)
})

The error object doesn't seem to have any code or anything else than message. err.code is undefined

How can I detect auth error?

/Not authorized/.test(err.message) seems hacky

mifi avatar Sep 02 '19 21:09 mifi

Have you tried calling authorizationStatusForType before trying to saveMindfulSession?

https://github.com/terrillo/rn-apple-healthkit/blob/master/docs/authorizationStatusForType().md

Luke-Gurgel avatar Sep 11 '19 18:09 Luke-Gurgel

Unfortunately that method is not available in the api. See #82

mifi avatar Sep 13 '19 19:09 mifi

Interesting, I was able to access that method in a dummy app I just created. It was pretty straightforward.

HealthKit.initHealthKit(options, async (err) => {
    if (err) return console.log("error initializing HealthKit", err);

    try {
      const res = await HealthKit.authorizationStatusForType('Height')
      console.log('res', res) // logs 'SharingAuthorized'
    } catch (e) {
      console.log('error', e)
    }
}

The method does seem to be available.

// RCTAppleHealthKit.m

RCT_EXPORT_METHOD(authorizationStatusForType:(NSString *)type
                  resolver:(RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)reject
{
    if (self.healthStore == nil) {
        self.healthStore = [[HKHealthStore alloc] init];
    }

    if ([HKHealthStore isHealthDataAvailable]) {
        HKObjectType *objectType = [self getWritePermFromString:type];
        if (objectType == nil) {
            reject(@"unknown write permission", nil, nil);
            return;
        }

        NSString *status = [self getAuthorizationStatusString:[self.healthStore authorizationStatusForType:objectType]];
        resolve(status);
    } else {
        reject(@"HealthKit data is not available", nil, nil);
    }
})

Luke-Gurgel avatar Sep 16 '19 12:09 Luke-Gurgel

It looks like that authorizationStatusForType code is not published to npm

Aleksandern avatar Sep 24 '19 06:09 Aleksandern