depicus

changing the digital world one bit at a time...

Blants (noun) the rants of a blogger

  1. Using HKBiologicalSexObject in HealthKit

    June 4, 2014 by The Man

    If you need to get the sex from Health then ask the normal way but add sex

    In your .h file

    @property (nonatomic, readwrite) HKHealthStore *healthStore;

    then in your .m file in didFinishLaunchingWithOptions or anywhere appropriate.

    // Set up an HKHealthStore, asking the user for read/write permissions.
        if ([HKHealthStore isHealthDataAvailable]) {
            self.healthStore = [[HKHealthStore alloc] init];
            NSSet *writeDataTypes = [self dataTypesToWrite];
            NSSet *readDataTypes = [self dataTypesToRead];
            
            [self.healthStore requestAuthorizationToShareTypes:writeDataTypes readTypes:readDataTypes completion:^(BOOL success, NSError *error) {
                
                if (!success) {
                    NSLog(@"You didn't allow HealthKit to access these read/write data types. In your app, try to handle this error gracefully when a user decides not to provide access. The error was: %@.", error);
                    return;
                }
                
                // Handle success in your app here.
                
            }];
        }
    

    Now we have healthStore and can ask for data… if we were ok above.

    HKBiologicalSexObject *sex = [self.healthStore biologicalSexWithError:&error];
        if (!error) {
            NSLog(@"you are %d sex",sex.biologicalSex);
            
            switch(sex.biologicalSex)
            {
                case 1:
                    // female
                    break;
                case 2:
                    // male
                    break;
                default:
                    // do nothing
                    break;
            }
        }
    
    

    which returns 0 for no sex, 1 for female and 2 for male.