lucaspbordignon / rn-apple-healthkit

A React Native package for interacting with Apple HealthKit
https://www.npmjs.com/package/react-native-health
MIT License
519 stars 296 forks source link

How to catch authorization error? #103

Open mifi opened 5 years ago

mifi commented 5 years ago

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

Luke-Gurgel commented 4 years ago

Have you tried calling authorizationStatusForType before trying to saveMindfulSession?

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

mifi commented 4 years ago

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

Luke-Gurgel commented 4 years ago

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);
    }
})
Aleksandern commented 4 years ago

It looks like that authorizationStatusForType code is not published to npm