Prerequisite(preparation)

Enable HealthKit

If you want to use HealthKit in your application, you first need to check the HealthKit option when generating the certificate.

Check Availability Check Availability

Given that HealthKit is currently only available on iPhone devices, not iPads or iPods, it is best to check usability before accessing HealthKit code:

if(NSClassFromString(@"HKHealthStore") && [HKHealthStore isHealthDataAvailable])
{
   // Add your HealthKit code here
}

Request authorization Authorization

Because HealthKit stores a large amount of user-sensitive information, if an App wants to access data in HealthKit, it first needs to request user permissions. Permissions are divided into read and write permissions (Apple calls read and write permissions share). Request permission is relatively simple, can be used directly requestAuthorizationToShareTypes: readTypes: completion: method.

HKHealthStore *healthStore = [[HKHealthStore alloc] init];

// Share body mass, height and body mass index
NSSet *shareObjectTypes = [NSSet setWithObjects:
                           [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass],
                           [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight],
                           [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMassIndex],
                           nil];

// Read date of birth, biological sex and step count
NSSet *readObjectTypes  = [NSSet setWithObjects:
                           [HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierDateOfBirth],
                           [HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierBiologicalSex],
                           [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount],
                           nil];

// Request access
[healthStore requestAuthorizationToShareTypes:shareObjectTypes
                                    readTypes:readObjectTypes
                                   completion:^(BOOL success, NSError *error) {

                                       if(success == YES)
                                       {
                                           // ...
                                       }
                                       else
                                       {
                                           // Determine if it was an error or if the
                                           // user just canceld the authorization request
                                       }

                                   }];

The above code will call the permission request interface as shown below:

The user has the option to accept or reject requests for reading or writing health data. The callback is invoked automatically after the request interface is determined or closed.

Read and write data

The way to read and write data from the HealthStore is straightforward, and the HKHealthStore class provides a lot of convenient ways to read basic properties. However, if you need to query in a more complex way, you can use a related subclass: HKQuery.

Physiological data

Gender and Age

NSError *error;
HKBiologicalSexObject *bioSex = [healthStore biologicalSexWithError:&error];

switch (bioSex.biologicalSex) {
    case HKBiologicalSexNotSet:
        // undefined
        break;
    case HKBiologicalSexFemale:
        // ...
        break;
    case HKBiologicalSexMale:
        // ...
        break;
}

weight

// Some weight in gram
double weightInGram = 83400.f;

// Create an instance of HKQuantityType and
// HKQuantity to specify the data type and value
// you want to update
NSDate          *now = [NSDate date];
HKQuantityType  *hkQuantityType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass];
HKQuantity      *hkQuantity = [HKQuantity quantityWithUnit:[HKUnit gramUnit] doubleValue:weightInGram];

// Create the concrete sample
HKQuantitySample *weightSample = [HKQuantitySample quantitySampleWithType:hkQuantityType
                                                                 quantity:hkQuantity
                                                                startDate:now
                                                                  endDate:now];

// Update the weight in the health store
[healthStore saveObject:weightSample withCompletion:^(BOOL success, NSError *error) {
    // ..
}];

Movement data

They count

// Set your start and end date for your query of interest
NSDate *startDate, *endDate;

// Use the sample type for step count
HKSampleType *sampleType = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];

// Create a predicate to set start/end date bounds of the query
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionStrictStartDate];

// Create a sort descriptor for sorting by start date
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:YES];


HKSampleQuery *sampleQuery = [[HKSampleQuery alloc] initWithSampleType:sampleType
                                                             predicate:predicate
                                                                 limit:HKObjectQueryNoLimit
                                                       sortDescriptors:@[sortDescriptor]
                                                         resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {
                                                            
                                                             if(!error && results)
                                                             {
                                                                 for(HKQuantitySample *samples in results)
                                                                 {
                                                                     // your code here
                                                                 }
                                                             }
                                                             
                                                         }];

// Execute the query
[healthStore executeQuery:sampleQuery];