HealthKit is simple to use

Keywords: Attribute Database

A Brief Introduction to HealthKit

At present, many App s will have access to health data, so we have to use HealthKit. The HealthKit framework provides a structure that applications can use to share health and fitness data. HealthKit manages data from different sources and automatically merges all data from different sources according to user preferences. The application can also retrieve the raw data from each source and then perform its own data merge.

How to integrate HealthKit in a project

This section will step by step integrate HealthKit into the project.

The first step is to add HealthKit

1. Enter the project settings --> Capabilities --> HealthKit, and then open it as follows. If the following options are checked before, then it represents OK, and generally no X will appear.

2. If the above steps are completed, there will be one more file in the project directory. This file is named after the project name, suffixed with entitlements, as follows:

3. There will be an additional HealthKit.framework file in the Frameworks directory:

Use in projects

First, import the HealthKit header file where health data needs to be accessed:

#import <HealthKit/HealthKit.h>

Then write an attribute:

@property (nonatomic, strong) HKHealthStore *healthStore;

1. This step instantiates a HKHealthStore object for your application. Each application requires only one HealthKit storage instance. This storage instance is your main interface to interact with the HealthKit database.

self.healthStore = [[HKHealthStore alloc] init];

2. Call the isHealthDataAvailable method to see if HealthKit is available on the device. HealthKit is not available on the iPad.

if ([HKHealthStore isHealthDataAvailable]) {
        NSLog(@"HealthDataAvailable");
    }

3. Specific code in the project:

//Create the data type you want to get
    HKObjectType *stepCpunt = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];//Step number
    HKObjectType *Height = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight];//height
    HKObjectType *BodyMass = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass];//weight
    HKObjectType *DistanceWalkingRunning = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];//Walking + Running Distance
    HKObjectType *DistanceCycling = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceCycling];//trip dist
    //A collection, data type
    NSSet *healthSet = [NSSet setWithObjects:stepCpunt,Height,BodyMass,DistanceWalkingRunning,DistanceCycling,nil];
    //[self.healthStore requestAuthorizationToShareTypes:nil readTypes:healthSet completion:nil];

    //Request data from the health APP of the system and call back the results
    [self.healthStore requestAuthorizationToShareTypes:nil readTypes:healthSet completion:^(BOOL success, NSError * _Nullable error) {
        if (success) {
            NSLog(@"requestAuthorization success");
            [self readHealthData:HKQuantityTypeIdentifierStepCount];
            [self readHealthData:HKQuantityTypeIdentifierDistanceWalkingRunning];
            [self readHealthData:HKQuantityTypeIdentifierDistanceCycling];
            [self readHealthData:HKQuantityTypeIdentifierHeight];
            [self readHealthData:HKQuantityTypeIdentifierBodyMass];
        }else{
        NSLog(@"requestAuthorization error");
        }
    }];

Operation of specific data acquisition

//Query data
- (void)readHealthData:(NSString* )HKQuantityTypeIdentifierType{
    //Query Sampling Information
    HKSampleType *sampleType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierType];

    //NSSortDescriptors are used to tell healthStore how to sort results.
    NSSortDescriptor *start = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO];
    NSSortDescriptor *end = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierEndDate ascending:NO];
    /*
     The base class of the query is HKQuery, which is an abstract class that can achieve each query target. Here we need to query the number of steps is one.
     HKSample So the corresponding query class is HKSampleQuery.
     The following limit parameter pass 1 indicates that the most recent data is queried. To query multiple data, just set the limit parameter value.
     Here we need to define what statements are executed in the block
     */
    HKSampleQuery *sampleQuery = [[HKSampleQuery alloc] initWithSampleType:sampleType predicate:nil limit:2 sortDescriptors:@[start,end] resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error) {
        //Print query results
        NSLog(@"resultCount = %ld result = %@",results.count,results);
        //Replace the result with a string type
        if (results.count!=0) {
        HKQuantitySample *result = results[0];
        HKQuantity *quantity = result.quantity;
        NSString *stepStr = (NSString *)quantity;
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            //Queries are done in multiple threads, and if you want to refresh the UI, you need to go back to the main thread.
            NSLog(@"Latest data:%@",stepStr);
        }];
        }else{
            NSLog(@"No health data");
        }
    }];
    //Execution query
    [self.healthStore executeQuery:sampleQuery];
}

Operation result

Ad locum

Posted by advancedfuture on Thu, 11 Apr 2019 22:03:32 -0700