HealthKit

Demo display effect

HealthKit
recordTime2.gif

Preface

With the increasing emphasis on health, the mobile terminal two giants Apple and Google have launched a health library of Apple Health, the Google Fit, they used the most integrated health fitness related data types, data of each application written according to their own areas of expertise, or other health data in the shared library, to to do their best, data sharing!

Sketch

The HealthKit framework provides a structure for applications that can be used to share health and fitness data. HealthKit manages data obtained from different sources and automatically merges all the data from different sources according to the preferences of the user. Applications can also obtain raw data from each source and then perform their own data merge. HealthKit also provides an application to help manage user health data. Health applications display HealthKit data for users. Users can use health applications to view, add, delete, or manage all of their health and fitness data. Users can also edit permissions to share each data type. HealthKit and health apps are not available on iPad.

Privacy

Because health data can be sensitive, HealthKit allows users to control these data by precisely controlling which information allows applications to read. The user must explicitly set the permissions for each application to read and write in the HealthKit store. Users can set permission or deny permissions for each data type individually. For example, users can allow your application to read step data, but it does not allow user heart rate data to be read. To prevent possible disclosure of information, the application does not know whether it is forbidden to read the data without invoking the associated access interface. HealthKit data will not be stored in iCloud, nor will it be synchronized between multiple devices. These data will only be stored in the user’s local device. For security reasons, the data stored by the HealthKit is encrypted when the device is not unlocked. In addition, if your application is not primarily providing health or fitness services, you cannot call HealthKit’s API. If your application provides health and fitness services, it must be explicitly indicated on the App Store related application profile and application interface.

Use HealthKit with special attention

  1. Your application should not use the data collected by HealthKit for advertising or similar services. Note that ads can be used in the HealthKit framework application, but you can’t use the data in the HealthKit to service the ad.
  2. You can’t show any data collected by HealthKit to any third party without the explicit permission of the user. You can only show the data to third parties that offer health or fitness services, even if the user allows.
  3. You can’t sell data collected by HealthKit to an advertising platform, data agent, or information distributor.
  4. If the user allows, you can share HealthKit data with third parties for medical research. Note that the user allows
  5. You must specify how you and your application will use the user’s HealthKit data.

HealthKit Store is used in the application, with special attention to App

  1. Be sure to add privacy policies, URL links, and privacy rules for health data usage. For example, in App, when you set your height and weight, XXX will write the information to apple health applications based on the permissions you have given. In App, when you synchronize, step, sleep, and heart rate data, XXX will write the information to apple health apps based on the permissions you have given before.
  2. The application must be noted: This version supports you to use Apple health application audit details, please refer to App Store Review HealthKit chapter Guidelines.

HealthKit design goals

HealthKit is used to share data between applications in a meaningful way. To achieve this, the framework restricts the use of predefined data types and units only. These limitations ensure that other applications understand what these data means and how to use them. As a result, developers cannot create custom data types and units. And HealthKit tries to provide a complete data type and unit.

HealthKit storage Philosophy

The framework heavily uses subclasses to create hierarchical relationships between similar classes. Usually these classes have some subtle but important differences. There are many classes associated with it that need to be properly matched to work together. The data stored in HealthKit is made up of objects and objects that belong to it. This concept must be engraved in mind so that you can understand the entire storage structure. All objects are based on HKObject, and all objects belong to the type based on HKObjectType. These two classes are briefly described below:

  • HKObject we can’t use it directly, but rather use its subclasses. Subclasses are: HKCategorySample, HKQuantitySample, HKCorrelation, HKWorkout
  • HKObject can be divided into two main categories: features and samples. A feature object represents some basic invariant data. For example: the user’s birthday, blood type and physiological sex, skin color. Your application cannot write to the feature data. Users must enter or modify these data through health applications. The sample object is data that is broken at a particular time. All sample objects are subclasses of HKSample. They all have the following attributes: sampleType: sample type. Example: a sleep analysis sample, a height sample, or a pedometer sample. StartDate: the start time of the sample. EndDate: the end time of the sample.
  • HKObject all objects are immutable (unless the source of the object is modified), and when you create an object, you need to set the object’s associated properties. All objects have the same attributes. As follows: the unique identifier UUID data source source version 9, with sourceRevision device to generate the object data of the device. The additional information that Metadata uses to describe objects is the NSDictionary type, where Key is the NSString type and Value can be NSString, NSNumber, and NSDate types. Where Key can be predefined or customizable. The predefined Key:NSString * * const const HKMetadataKeyDeviceSerialNumber; NSString HKMetadataKeyBodyTemperatureSensorLocation; NSString * const HKMetadataKeyHeartRateSensorLocation NSString * const; HKMetadataKeyFoodType; NSString * const HKMetadataKeyUDIDeviceIdentifier NSString * const; HKMetadataKeyUDIProductionIdentifier; NSString * const HKMetadataKeyDigitalSignature NSString * const; HKMetadataKeyExternalUUID; NSString * const HKMetadataKeyTimeZone NSString * const; HKMetadataKeyDeviceName; NSString * const HKMetadataKeyDeviceManufacturerName NSString * const; HKMetadataKeyWasTakenInLab; NSString * const HKMetadataKeyReferenceRangeLowerLimit NSString * const; HKMetadataKeyReferenceRangeUpperLimit; NSString * const HKMetadataKey WasUserEntered; NSString * const HKMetadataKeyWorkoutBrandName NSString * const; HKMetadataKeyGroupFitness; NSString * const HKMetadataKeyIndoorWorkout NSString * const; HKMetadataKeyCoachedWorkout; NSString * const HKMetadataKeySexualActivityProtectionUsed NSString * const HKMetadataKeyMenstrualCycleStart;
  • HKObjectType is used to describe the type of HKObject. We can’t use it directly; we can only use its subclasses to distinguish data types. Its subclasses are: HKQuantityType, HKCategoryType, HKCharacteristicType, HKActivitySummaryType, HKCorrelationType, HKDocumentType, HKWorkoutType
  • The method for initializing type subclasses is:
(nullable * HKQuantityType) + quantityTypeForIdentifier: (NSString *) identifier + (nullable * HKCategoryType); categoryTypeForIdentifier: (NSString *) identifier + (nullable * HKCharacteristicType); characteristicTypeForIdentifier: (NSString *) identifier + (nullable * HKCorrelationType); correlationTypeForIdentifier: (NSString * identifier);
  • The Identifiers of the predefined type of system has:
/*--------------------------------*/ / * HKQuantityType Identifiers * HK_EXTERN * NSString /*--------------------------------*/ / / Body Measurements const HKQuantityTypeIdentifierBodyMassIndex NS_AVAILABLE_IOS (8_0); / / Scalar (Count), Discrete HK_EXTERN NSString * const HKQuantityTypeIdentifierBodyFatPercentage NS_AVAILABLE_IOS (8_0); / / Scalar (Percent, 0 - 1), Discrete HK_EXTERN NSString * const HKQuantityTypeIdentifierHeight NS_AVAILABLE_IOS (8_0); / / Length, Discrete HK_EXTERN NSString * const HKQuantityTypeIdentifierBodyMass NS_AVAILABLE_IOS (8_0); / / Mass, Discrete HK_EXTERN NSString * const HKQuantityTypeIdentifierL EanBodyMass NS_AVAILABLE_IOS (8_0); / / Mass, Discrete / / Fitness HK_EXTERN NSString * const HKQuantityTypeIdentifierStepCount NS_AVAILABLE_IOS (8_0); / / Scalar (Count), Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDistanceWalkingRunning NS_AVAILABLE_IOS (8_0); / / Length, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDistanceCycling NS_AVAILABLE_IOS (8_0); / / Length, Cumulative HK_EXTERN NSString (NS_AVAILABLE_IOS * const HKQuantityTypeIdentifierBasalEnergyBurned 8_0); / / Energy, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierActiveEnergyBurned NS_AVA ILABLE_IOS (8_0); / / Energy, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierFlightsClimbed NS_AVAILABLE_IOS (8_0); / / Scalar (Count), Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierNikeFuel NS_AVAILABLE_IOS (8_0); / / Scalar (Count), Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierAppleExerciseTime HK_AVAILABLE_IOS_WATCHOS (9_3, 2_2); / / Time / / Cumulative Vitals HK_EXTERN NSString * const HKQuantityTypeIdentifierHeartRate NS_AVAILABLE_IOS (8_0); / / Scalar (Count) /Time, Discrete HK_EXTERN NSString * const HKQuantityTypeIdentifierBodyTemperature NS_AVAILABLE_IOS (8_0); Discrete HK_EXTERN / / Temperature, NSString * const HKQuantityTypeIdentifierBasalBodyTemperature NS_AVAILABLE_IOS (9_0); / / Basal Body Temperature Discrete HK_EXTERN NSString * const HKQuantityTypeIdentifierBloodPressureSystolic NS_AVAILABLE_IOS (8_0); / / Pressure, Discrete HK_EXTERN NSString * const HKQuantityTypeIdentifierBloodPressureDiastolic NS_AVAILABLE_IOS (8_0); / / Pressure, Discrete HK_EXTERN NSString * const HKQuantityTypeIdentifierRespiratoryRate NS_AVAILABLE_IOS (8_0); / / Scalar (Count) /Time Discrete, HK_EXTERN * const HKQuantityTypeIdentifierOxygenSaturation / / Results NSString NS_AVAILABLE_IOS (8_0); / / Scalar (Percent, 0 - 1, Discrete HK_EXTERN NSString * const HKQuantityTypeIdentifierPeripheralPerfusionIndex NS_AVAILABLE_IOS (8_0); / / Scalar (Percent, 0 - 1), Discrete HK_EXTERN NSString * const HKQuantityTypeIdentifierBloodGlucose NS_AVAILABLE_IOS (8_0); / / Mass/Volume, Discrete HK_EXTERN NSString * const HKQuantityTypeIdentifierNumberOfTimesFallen NS_AVAILABLE_IOS (8_0); / / Scalar (Count), Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierElectrodermalActivity NS_AVAILABLE_IOS (8_0) Discrete; / / Conductance, HK_EXTERN NSString * const HKQuantityTypeIdentifierInhalerUsage NS_AVAILABLE_IOS (8_0); / / Scalar (Count), Cumulative HK_EXTERN NSString * con St HKQuantityTypeIdentifierBloodAlcoholContent NS_AVAILABLE_IOS (8_0); / / Scalar (Percent, 0 - 1), Discrete HK_EXTERN NSString * const HKQuantityTypeIdentifierForcedVitalCapacity NS_AVAILABLE_IOS (8_0); / / Volume, Discrete HK_EXTERN NSString * const HKQuantityTypeIdentifierForcedExpiratoryVolume1 NS_AVAILABLE_IOS (8_0); / / Volume, Discrete HK_EXTERN NSString * const HKQuantityTypeIdentifierPeakExpiratoryFlowRate NS_AVAILABLE_IOS (8_0); / / Volume/Time, Discrete / / Nutrition HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryFatTotal NS_AVAILABLE_IOS (8_0); / / Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryFatPolyunsatura Ted NS_AVAILABLE_IOS (8_0); / / Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryFatMonounsaturated NS_AVAILABLE_IOS (8_0); / / Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryFatSaturated NS_AVAILABLE_IOS (8_0); / / Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryCholesterol NS_AVAILABLE_IOS (8_0); / / Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietarySodium NS_AVAILABLE_IOS (8_0); / / Mass Cumulative, HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryCarbohydrates NS_AVAILABLE_IOS (8_0); / / Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryFiber NS_AVAILABLE_IOS (8_0); Cumulative HK_EXTERN / / Mass, NSString * const HKQuantityTypeIdentifierDietarySugar NS_AVAILABLE_IOS (8_0); / / Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryEnergyConsumed NS_AVAILABLE_IOS (8_0); / / Energy, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryProtein NS_AVAILABLE_IOS (8_0); / / Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryVitaminA NS_AVAILABLE_IOS (8_0); / / Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryVitaminB6 NS_AVAILABLE_IOS (8_0); / / Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryVitaminB12 NS_AVAILABLE_IOS (8_0); / / Mass, C Umulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryVitaminC NS_AVAILABLE_IOS (8_0); / / Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryVitaminD NS_AVAILABLE_IOS (8_0); / / Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryVitaminE NS_AVAILABLE_IOS (8_0); / / Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryVitaminK NS_AVAILABLE_IOS (8_0); / / Mass, Cumulative HK_EXTERN NSString (NS_AVAILABLE_IOS * const HKQuantityTypeIdentifierDietaryCalcium 8_0); / / Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryIron NS_AVAILABLE_IOS (8_0); / / Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryThiamin NS_AVAILABLE_IOS (8_0); / / Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryRiboflavin NS_AVAILABLE_IOS (8_0); / / Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryNiacin NS_AVAILABLE_IOS (8_0); / / Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryFolate NS_AVAILABLE_IOS (8_0); / / Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryBiotin NS_AVAILABLE_IOS (8_0); Cumulative HK_EXTERN / / Mass, NSString * const HKQuantityTypeIdentifierDietaryPantothenicAcid NS_AVAILABLE_IOS (8_0); / / Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentif IerDietaryPhosphorus NS_AVAILABLE_IOS (8_0); / / Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryIodine NS_AVAILABLE_IOS (8_0); / / Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryMagnesium NS_AVAILABLE_IOS (8_0); / / Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryZinc NS_AVAILABLE_IOS (8_0); / / Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietarySelenium NS_AVAILABLE_IOS (8_0); / / Mass Cumulative, HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryCopper NS_AVAILABLE_IOS (8_0); / / Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryManganese NS_AVAILA BLE_IOS (8_0); / / Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryChromium NS_AVAILABLE_IOS (8_0); / / Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryMolybdenum NS_AVAILABLE_IOS (8_0); / / Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryChloride NS_AVAILABLE_IOS (8_0); / / Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryPotassium NS_AVAILABLE_IOS (8_0); / / Mass. Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryCaffeine NS_AVAILABLE_IOS (8_0); / / Mass, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierDietaryWater NS_AVAILABLE_IOS (9_0); / / Vol Ume, Cumulative HK_EXTERN NSString * const HKQuantityTypeIdentifierUVExposure NS_AVAILABLE_IOS (9_0); / / Scalar (Count), Discrete /*--------------------------------*/ / * HKCategoryType Identifiers * / NSString * const HKCategoryTypeIdentifierSleepAnalysis NS_AVAILABLE_IOS HK_EXTERN /*--------------------------------*/ (8_0); / / HKCategoryValueSleepAnalysis HK_EXTERN NSString * const HKCategoryTypeIdentifierAppleStandHour NS_AVAILABLE_IOS (9_0); / / HKCategoryValueAppleStandHour HK_EXTERN NSString * const HKCategoryTypeIdentifierCervicalMucusQuality NS_AVAILABLE_IOS (9_0); / / HKCategoryValueCervicalMucusQuality HK_EXTERN NSString * const HKCategoryTypeIdentifierOvulationTestResult NS_AVAILABLE_IOS (9_0); / / HKCategoryValueOvulationTestResult HK_EXTERN NSString * const HKCategoryTypeIdentifierMenstrualFlow NS_AVAILABLE_IOS (9_0); / / HKCategoryValueMenstrualFlow HK_EXTERN
  • Among them, we usually have HKQuantityType, HKCategoryType is also used in my application type.

How to use

  • Create a project named “HealthKit”
  • Xcode8.0, iOS 10 after the need to add read and write instructions in the Info.plist file, whether it feels deja vu, in fact, it and the use of positioning function, you need to add instructions in Info.plist, a truth. (the instructions in Demo only tell you the corresponding description of the read or write operation only, describe yourself according to the actual situation of the application described), as shown in the following figure:
HealthKit
screen snapshot 2016-09-24 12.22.54.png
  • Open the -&gt at TAGETS-> Capabilities; HealthKit as shown below:
HealthKit
screen snapshot 2016-09-20 22.12.44.png

at this point, the project will automatically add HealthKit.framework to the project.

  • Create a class that manages our HealthKit related operations: ZHHealthManager, which includes requests for access to the HealthKit library and related read-write operations. ZHHealthManager.h file correlation method
#import < Foundation/Foundation.h> #import; < HealthKit/HealthKit.h> typedef void (^ZHHealthKitFinishBlock) (BOOL success, NSError *error); typedef void (^ZHHealthKitIntegerValueBlock) (NSInteger value, NSError *error); @interface ZHHealthManager: NSObject @property (nonatomic) HKHealthStore * healthStore; + (ZHHealthManager *) shareZHHealthManager request Authorization To Share; / * * * Data in HealthKit * * @param finish block * / - (void) requestAuthorizationToShareWithCompletion: (ZHHealthKitFinishBlock) finish Read User Age; / * * * * * @param finish finish * / block. - (void) readUsersAgeWithFinish: (ZHHealthKitIntegerValueBlock) finish write height data into; / * * * HealthKit * * @param height height * @param `cm` Unit unit Option * @param finish block * / - (void) saveHeightIntoHealthStore: (double) height withCompletion: (ZHHealthKitFinishBlock) finish write weight data into; / * * * HealthKit * * @param weight weight `kg` unit unit option * @param * @param finish finishBlock * / - (void) saveWeightIntoHealthStore: (double) weight withCompletion: (ZHHealthKitFinishBlock) finish; / * * * save stepcount into HealthKit @param steps steps * * * @param startDate startDate * @param endDate endDate * @param finish Block * / - (void) saveStepCount: (NSInteger) steps startTime: (NSDate * startDate) endTime: (NSDate *) endDate withCompletion: (ZHHealthKitFinishBlock) finish save walk distance into; / * * * healthKit * * @param walkDistanc E walk distance * @param startDate startDate * @param endDate endDate * @param finish block * / - (void) saveWalkDistance: (double) walkDistance startTime: (NSDate * startDate) endTime: (NSDate *) endDate withCompletion: (ZHHealthKitFinishBlock) finish save active Energy burn; / * * * calories into healthKit * * @param calories calories * @param startDate startDate * @param endDate endDate * @param finish block * / - (void) saveActiveEnergyBurnCalories: (double) calories startTime: (NSDate * startDate) endTime: (NSDate *) endDate withCompletion: (ZHHealthKitFinishBlock) finish save heartRate into HealthKit; / * * * * * @param heartRate heartRate * @param finish block * / - (void) saveHeartRate: (NSInteger) heartRate WithCompletion: (ZHHealthKitFinishBlock) finish save sleep data into; / * * * HealthKit * * @param startDate start time endDate end time * @param * @param finish finish * / block - (void) saveSleepWithstartTime: (NSDate * startDate) endTime: (NSDate *) endDate withCompletion: (ZHHealthKitFinishBlock) finish; @end

Method call

  • First of all, we need to write down the types of data that we want to read or write.
#pragma mark - Health Kit - TypesToWrite (NSSet * dataTypesToWrite) {HKQuantityType *stepCountQuantityType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount]; HKQuantityType *walkDistanceQuantityType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning]; HKQuantityType *activeEnergyBurnQuantityType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned]; HKQuantityType *heartQuantityType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate] HKCategoryType [HKCategoryType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis]; *sleepCategoryType = HKQuantityType; *heightType = [HKObjectType Q UantityTypeForIdentifier:HKQuantityTypeIdentifierHeight]; HKQuantityType *weightType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass]; return [NSSet setWithObjects:stepCountQuantityType, walkDistanceQuantityType, activeEnergyBurnQuantityType, sleepCategoryType, heartQuantityType, heightType, weightType, nil]; #pragma mark Kit TypesToRead} - Health - (NSSet * dataTypesToRead) {HKCharacteristicType *ageTypte = [HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierDateOfBirth]; return [NSSet setWithObjects:ageTypte nil];}
  • Then apply for access to read and write operations.
- (void) requestAuthorizationToShareWithCompletion: (ZHHealthKitFinishBlock finish) {if ([HKHealthStore isHealthDataAvailable]) {NSSet *writeDataTypes = [self dataTypesToWrite]; NSSet *readDataTypes = [self dataTypesToRead]; requestAuthorizationToShareTypes:writeDataTypes readTypes:readDataTypes completion:^ [self.healthStore (BOOL success, NSError *error) {if (finish) {finish (success, error);}}];}else{*userInfo = NSLocalizedString (@{NSLocalizedDescriptionKey: NSDictionary @ health applications is not available! "," @ health applications is not available! "), NSLocalizedFailureReasonErrorKey: NSLocalizedString (@ Health Kit not @ available.", "Health Kit not available."), NSLocalizedRecov ErySuggestionErrorKey: NSLocalizedString (@ Have you tried turning it off and on again? "," Have you tried turning @ it off and on again? ")}; NSError *error = [NSError errorWithDomain:NSPOSIXErrorDomain code:-10 userInfo:userInfo]; if (finish) {finish (NO, error);} NSLog (@ Health Kit not available")}};
  • After access to permissions to read or write related operations, important to remember three points. Judge system version, less than 8 unavailable. Determine whether the device supports HealthKit. [HKHealthStore isHealthDataAvailable]. Determine whether the user is authorized for this type. AuthorizationStatusForType (excluding immutable data types, such as birthdays, genders, blood types, etc.), does not make any judgments about authorization. There is usually no problem. Errors can also occur when reading and writing operations. However, for data manipulation, system judgment is more time consuming and sometimes inexplicable errors occur.
  • Here are two examples of how to read the age. Write the height.

Age reading operation

- (void) readUsersAgeWithFinish: (ZHHealthKitIntegerValueBlock) finish systemVersion currentDevice].systemVersion floatValue] {NSInteger = [[UIDevice; if (systemVersion < 8) {// system less than 8 / return;} if ([HKHealthStore! IsHealthDataAvailable]) / / health is not available directly back {return}; NSError *error; NSDate *dateOfBirth = [self.healthStore dateOfBirthWithError:& error] NSInteger; age = -1 age did not get to return; / / 1 if (dateOfBirth) {// read on students into age NSDate *now = [NSDate date]; NSDateComponents *ageComponents = [[NSCalendar currentCalendar] components:NSCalendarUnitYear fromDate:dateOfBirth toDate:now options:NSCalendarWrapComponent S]; NSUInteger usersAge = [ageComponents year]; age = usersAge;} if (finish) {finish (age, error)}}

Height write operation

- (void) saveHeightIntoHealthStore: (double) height withCompletion: (ZHHealthKitFinishBlock) finish systemVersion currentDevice].systemVersion floatValue] {NSInteger = [[UIDevice; if (systemVersion < 8) {// system less than 8 / return;} if ([HKHealthStore! IsHealthDataAvailable]) / / health is not available directly back {return;} HKQuantityType *weightType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass] ([self.healthStore authorizationStatusForType:weightType]; if! = HKAuthorizationStatusSharingAuthorized) {NSLog (@ without user permission access directly return "); return;} HKUnit *hkUnit = [HKUnit inchUnit]; height = height/100; hkUnit = [HKUnit MeterUnit]; HKQuantity *heightQuantity = [HKQuantity quantityWithUnit:hkUnit doubleValue:height]; HKQuantityType *heightType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight]; if ([self.healthStore authorizationStatusForType:heightType]) {} NSDate *now = [NSDate date]; HKQuantitySample *heightSample = [HKQuantitySample quantitySampleWithType:heightType quantity:heightQuantity startDate:now endDate:now] [self.healthStore saveObject: heightSample; withCompletion:^ (BOOL success, NSError *error) {if (finish) {finish (success, error);}}];}
  • Of course, in other sample operations, such as: step, sleep, and so on. If there is a possibility of repeated writes, we need to first determine whether the data has been stored in HealthKit for that period. Query operations will be used here, you can refer to my Demo in the HKHealthStore+ZHHKExtensions class.

Demo download address

GitHub