The HealthKit Framework

The HealthKit framework provides a structure that apps can use to share health and fitness data. HealthKit is designed to manage data from a wide range of sources, automatically merging the data from all the different sources based on users’ preferences. Apps can also access the raw data for each source and let the app perform its own merging.

HealthKit also works directly with health and fitness devices. In iOS 8.0, the system can automatically save data from compatible Bluetooth LE heart rate monitors directly into the HealthKit store. The system can also automatically import step count data from the M7 motion coprocessor, if available. Other devices and data sources must have a companion app that can access the data and save it to HealthKit for them.

HealthKit also provides an app to help manage the user’s health data. The Health app acts as the user’s interface to the HealthKit data. Users can view, add, delete, and otherwise manage all of their health and fitness data using this app. They can also edit the sharing permissions for each data type.

Both HealthKit and the Health app are unavailable on iPad. The HealthKit framework cannot be used in an app extension.

HealthKit and Privacy

Because health data can be sensitive, HealthKit grants users control over their data by providing fine-grained control over the information that apps can share. The user must explicitly grant each app permission to read and write data to the HealthKit store. Users can grant or deny permission separately for each type of data. For example, a user could let your app read the step count data but prevent it from reading the blood glucose level. To prevent possible information leaks, an app does not know whether it has been denied permission to read data. From the app’s point of view, if the app has been denied permission to read data, no data of that type exists.

The HealthKit data is only kept locally on the user’s device. For security, the HealthKit store is encrypted when the device is not unlocked. The HealthKit store can only be accessed by an authorized app. You cannot access HealthKit from extensions (like the Today view) or from a WatchKit app.

NOTE

Because the HealthKit store is encrypted, your app cannot read data from the store when the phone is locked. This means your app may not be able to access the store when it is launched in the background. However, apps can still write data to the store, even when the phone is locked. The store temporarily caches the data and saves it to the encrypted store as soon as the phone is unlocked.

In addition, your app must not access the HealthKit APIs unless the app is primarily designed to provide health or fitness services. Your app's role as a health and fitness service must be clear in both your marketing text and your user interface. Specifically, the following guidelines apply to all HealthKit apps.

  • Your app may not use information gained through the use of the HealthKit framework for advertising or similar services. Note that you may still serve advertising in an app that uses the HealthKit framework, but you cannot use data from the HealthKit store to serve ads.

  • You must not disclose any information gained through HealthKit to a third party without express permission from the user. Even with permission, you can only share information to a third party if they are also providing a health or fitness service to the user.

  • You cannot sell information gained through HealthKit to advertising platforms, data brokers or information resellers.

  • If the user consents, you may share his or her HealthKit data with a third party for medical research.

  • You must clearly disclose to the user how you and your app will use their HealthKit data.

You must also provide a privacy policy for any app that uses the HealthKit framework. You can find guidance on creating a privacy policy at the following sites:

These models developed by the ONC are designed to improve user experience and understanding by using plain language and approachable designs to explain how user data is collected and shared. These are not intended to replace a web based privacy policy, and developers should consult ONC guidance regarding which model is appropriate for a given app. These models are provided for your reference only, and Apple expressly disclaims all liability for your use of such models.

NOTE

This section provides guidelines to help you create a HealthKit app that respects user privacy. It’s essential that you understand Apple’s requirements for working with HealthKit and the user’s health-related data. To learn about these requirements, see the HealthKit section in App Store Review Guidelines, which is available from Apple’s App Review Support page.

For additional technical information about working with sensitive user data, see Best Practices for Maintaining User Privacy in App Programming Guide for iOS.

Benefits from Adopting HealthKit

Health and fitness apps gain several concrete benefits from adopting HealthKit. Some of the main benefits are listed below.

Separating data collection, data processing, and socialization. The modern health and fitness experience involves many different facets, such as collecting and analyzing data, providing actionable information and useful visualizations to the user, and allowing users to participate in a social community. HealthKit frees each app from the responsibility of implementing all of these aspects. Instead, you can focus on implementing only the aspects you are most interested in, leaving the other tasks to more specialized apps.

This separation of responsibility also benefits the users. Each user can freely select their favorite weight tracking app, step counting app, and health challenge app. This mix-and-match approach means that users can select a suite of apps, with each app finely tuned to their exact needs. However, because these apps can freely exchange data, the combined suite provides a better experience than any single app could on its own.

For example, a group of friends could decide to join a daily step-count challenge. Each person could use his or her preferred hardware device or app to track the steps, but they could all still use the same social app for the challenge.

Reduces friction in sharing between apps. HealthKit makes it easier to share data between apps. For developers, you no longer need to download APIs and write custom code to share with each app. As new HealthKit apps become available, they can begin sharing automatically through the HealthKit store.

Users benefit, because they don’t need to manually set up the connections between their apps or import and export their data. Importantly, users still control which apps can read and write data to the HealthKit store—and exactly what pieces of data each app has access to. However, as soon as the user grants permission, apps can freely and frictionlessly access each other’s data.

Providing a richer set of data and a greater sense of context. Apps can benefit by accessing a wider range of data, giving each app a more complete view of the user’s health and fitness needs. In many cases, an app can modify its metrics or advice based on the additional information from the HealthKit store. For example, a training app could suggest a post workout snack based not only on the number of calories that the user has burned but also on the type and amount of food he or she has eaten so far that day.

Lets apps participate in a greater ecosystem. Apps benefit by sharing the data they collect with HealthKit. Becoming part of a larger ecosystem helps increase the visibility and utility of your app. More important, by adopting HealthKit you let your app collaborate with other apps that the users already owns and loves. If they cannot share data between your app and the other apps that they are already using, they may decide to look for a solution elsewhere.

HealthKit’s Design Philosophy

The HealthKit framework is designed to share data between apps in a meaningful way. To that end, the framework constrains the types of data and units to a predefined list. These limits ensure that other apps understand both what the data means and how it can be used. As a result, developers cannot create custom data types or units. Instead, HealthKit attempts to provide a reasonably complete list of data types and units.

The framework also uses subclassing aggressively, producing hierarchies of similar classes. Often, these classes have subtle but important differences between them. There are also a number of closely related classes that must be correctly paired before they can work together successfully. For example, the HKObject and HKObjectType abstract classes have largely parallel hierarchies of concrete subclasses. When working with objects and object types, you must be sure to use matching subclasses.

All objects in the HealthKit store are subclasses of the HKObject class. Most HealthKit object subclasses are immutable. Each object has the following properties:

  • UUID. A unique identifier for that particular entry.

  • Source. The source of the data. The source can be a device that directly saves data into HealthKit, or an app. HealthKit automatically sets each object’s source when the object is saved to the HealthKit store. This property is available only on objects retrieved from the store.

  • Metadata. A dictionary containing additional information about the entry. The metadata can contain both predefined and custom keys. The predefined keys help facilitate the sharing of data between apps. Custom keys help extend a given HealthKit object type, adding app-specific data to the entry.

HealthKit objects can be divided into two main groups: characteristics and samples. Characteristic objects represent data that typically does not change. This data includes the user’s birthdate, blood type, and biological sex. Your application cannot save characteristic data. The user must enter or modify this data using the Health app.

Sample objects represent data at a particular point in time. All sample objects are subclasses of the HKSample class. They all have the following properties:

  • Type. The sample type. For example, this could include a sleep analysis sample, a height sample, or a step count sample.

  • Start date. The starting time for the sample.

  • End date. The ending time for the sample. If the sample represents a single point in time, the end time should equal the start time. If the sample represents data collected over a time interval, the end time should occur after the start time.

Samples can be further partitioned into four sample types.

  • Category samples. These samples represent data that can be classified into a finite set of categories. In iOS 8.0, there is only one type of category sample, sleep analysis. For more information, see HKCategorySample Class Reference.

  • Quantity samples. These samples represent data that can be stored as numeric values. Quantity samples are the most common data types in HealthKit. These include the user’s height and weight, as well as other data such as the number of steps taken, the user’s temperature, and their pulse rate. For more information, see HKQuantitySample Class Reference.

  • Correlations. These samples represent composite data—data that contains one or more samples. In iOS 8.0, HealthKit uses correlations to represent food and blood pressure. You should always use a correlation when creating food or blood pressure data. For more information, see HKCorrelation Class Reference.

  • Workouts. Workouts represent some sort of physical activity, like running, swimming, or even play. Workouts often have typeduration,distance, and energy burned properties. You can also associate a workout with a number of fine-grained samples. Unlike correlations, these samples are not contained within the workout—however, they can be queried using the workout. For more information, see HKWorkout Class Reference.

Setting Up HealthKit

Before you can begin using HealthKit, you must perform the following steps:

  1. Enable the HealthKit capabilities in Xcode.

    NOTE

    When you enable the HealthKit capabilities, Xcode adds HealthKit to the list of required device capabilities. This prevents users from purchasing or installing the app on devices that do not support HealthKit.

    If HealthKit is not required for the correct operation of your app, you can open the app’s info.plist file and delete the healthkit entry from the Required device capabilities array.

    For more information on required device capabilities, see the UIRequiredDeviceCapabilities key in Information Property List Key Reference.

  2. Check to see whether HealthKit is available by calling the isHealthDataAvailable method. HealthKit is not available on iPad. Additionally, HealthKit can be disabled on other devices—for example, iPhones that are provisioned for schools or corporate environments.

  3. Instantiate an HKHealthStore object for your app. You need only one HealthKit store per app. This store acts as your primary interface with the HealthKit database.

  4. Request authorization to access HealthKit data using the requestAuthorizationToShareTypes:readTypes:completion: method. HealthKit requires fine-grained authorization. You must request permission to share and read each type of data.

    You can also provide custom messages for the permission sheet using the NSHealthShareUsageDescription and NSHealthUpdateUsageDescriptionkeys in your app’s info.plist file.

    NOTE

    The first time you request permission for a data type, the system presents a permission sheet and stores the user’s response. On each subsequent request, the system uses the stored permissions. Users can modify their permissions in either the Health or Settings apps.

After requesting authorization, your app is ready to access the HealthKit store. If your app has permission to share a data type, it can create and save samples of that type. You should verify that your app has permission to share data by calling authorizationStatusForType: before attempting to save any samples.

If your app has permission to read a data type, you can query that data from the HealthKit store; however, even knowing that the user has denied your request to read data could reveal private health information. Therefore, your app cannot determine whether it has permission to read a particular type of data. If the user does not grant permission, queries for the restricted data types return only the samples that your app has shared. Otherwise, the HealthKit store appears to be empty.

For more information on setting up HeathKit, see HKHealthStore Class Reference.

For a practical example, demonstrating how to setup and use HealthKit, see Fit: Store and Retrieve HealthKit Data.

Adding Samples to the HealthKit Store

Your app can create new samples and add them to the HealthKit store. The general procedure is similar for all sample types, though each type has its own variations on this theme.

  1. Look up the correct type identifier in HealthKit Constants Reference.

  2. Create a matching HKObjectType subclass, using the type identifier. For a list of convenience methods, see HKObjectType Class Reference.

  3. Create a matching HKSample subclass, using the object type.

  4. Save the object to the HealthKit store using the saveObject:withCompletion: method.

Each HKSample subclass has its own convenience methods for instantiating its sample objects. These methods modify the procedure as described below.

image: ../Art/quantity_sample_2x.png

For quantity samples, you must create an instance of the HKQuantity class. The quantity’s units must correspond to the allowable units described in the type identifier’s documentation. For example, the HKQuantityTypeIdentifierHeight documentation states that it uses length units. Therefore, your quantity must use centimeters, meters, feet, inches, or another compatible unit. For more information, see HKQuantitySample Class Reference.

image: ../Art/category_sample_2x.png

For category samples, the value must correspond to the enum described in the type identifier’s documentation. For example, theHKCategoryTypeIdentifierSleepAnalysis documentation states that it uses the HKCategoryValueSleepAnalysis enum. Therefore, you must pass a value from this enum when creating this sample. For more information, see HKCategorySample Class Reference.

image: ../Art/correlation_sample_2x.png

For correlations, you must first create all the sample objects that the correlation will contain. The correlation’s type identifier describes both the type and the number of objects that can be contained. Do not save the contained objects into the HealthKit store. They are stored as part of the correlation. For more information, see HKCorrelation Class Reference.

image: ../Art/workout_sample_2x.png

Workouts behave somewhat differently than other samples. First, you do not need a specific type identifier to create the HKWorkoutType instance. All workouts use the same type identifier. Second, you will need to provide an HKWorkoutActivityType value for each workout. This value defines the type of activity performed during the workout. Finally, after the workout is saved to the HealthKit store, you may associate additional samples with the workout. These samples provide fine-grained details about the workout. For more information, see HKWorkout Class Reference.

Accessing HealthKit Data

The HealthKit store provides a number of methods for accessing its data.

  • Direct method calls. The HealthKit store provides methods to directly access characteristic data. These methods can be used only to access characteristic data. For more information, see HKHealthStore Class Reference.

  • Sample query. This is a general-purpose query. Use sample queries to access any type of sample data. Sample queries are particularly useful when you want to sort the results or limit the total number of samples returned. For more information, see HKSampleQuery Class Reference.

  • Observer query. This is a long-running query that monitors the HealthKit store and alerts you to any changes to matching samples. Use observer queries when you want to be notified about changes to the store. You can register these queries for background delivery. For more information, see HKObserverQuery Class Reference.

  • Anchored object query. Use this query to search for items that have been added to the store. The first time an anchor query is run, it returns all the matching samples in the store. On subsequent runs, it returns only those items that have been added since the last run. You will often use anchored object queries with observer queries. The observer query tells you when something has changed. The anchored object query determines what (if anything) has been added to the store. For more information, see HKAnchoredObjectQuery Class Reference.

  • Statistics query. Use this query to perform statistical calculations over the set of matching samples. You can use statistics queries to calculate the sum, minimum, maximum, or average value in the set. For more information, see HKStatisticsQuery Class Reference.

  • Statistics collection query. Use this query to perform multiple statistics queries over a series of fixed-length time intervals. You will often use these queries when creating graphs. They provide a simple method for calculating things such as the total number of calories consumed each day or the number of steps taken in each 5-minute interval. Statistics collection queries are long-running queries. While they can return the current collection of statistics, they can also monitor the HeathKit store and respond to updates. For more information, seeHKStatisticsCollectionQuery Class Reference.

  • Correlation query. Use this query to perform complex searches of the data contained in a correlation. These queries can contain individual predicates for each of the sample types stored in the correlation. If you just want to match the correlation type, use a sample query instead. For more information, see HKCorrelation Class Reference.

  • Source query. Use this query to search for sources (apps and devices) that have saved matching data to the HealthKit store. A source query lists all the sources that are saving a particular sample type. For more information, see HKSourceQuery Class Reference.

Working with Units

HealthKit provides support for units using the HKUnit and HKQuantity classes. HKUnit provides the representation for a single unit. It supports a wide range of metric and imperial units, as well as both simple and complex units. A simple unit represents a single measurement, such as meters, pounds or seconds. A complex unit combines one or more simple units using mathematical operations, such m/s or lb/ft2.

The HKUnit class provides convenience methods to create all the simple units supported by HealthKit. It also provides the mathematical operations needed to build complex units. Finally, you can create complex units directly using properly formatted unit strings.

For more information on units, see HKUnit Class Reference.

The HKQuantity class stores a value for a given unit. You can then request the value in any compatible units. In this way, your app easily translate values between units.

For more information on quantities, see HKQuantity Class Reference.

In some instances you can localize quantities using formatters. iOS 8 provides new formatters for length (NSLengthFormatter), mass (NSMassFormatter), and energy (NSEnergyFormatter). For other quantities, you will need to perform the conversions and localize the data yourself.

Threading

The HealthKit store is thread-safe, and most HealthKit objects are immutable. In general, you can use HealthKit safely in a multithreaded environment.

NOTE

All the HealthKit API’s completion handlers execute on private background queues. You will typically want to dispatch this data back to the main queue before updating your user interface or modifying any other resources that should be touched only by the main thread.

For more information about multithreading and concurrent programming, see Concurrency Programming Guide.

Adding Digital Signatures

The digital signature metadata object in HealthKit is intended to provide data integrity for sample records generated by a trusted device. This metadata item stores a digitally signed copy of the sample record. The signature is generated by the device (which should be tamper resistant, since it stores the private signature key). This allows a data consumer to check the signature against a known public key for that device to verify that the record data has not been altered. Since each record is signed individually, storage overhead is on the order of 1K bytes per record. Thus, this meta data signature item is intended for records where the sample rate is up to a few times per day. Higher sample rates will require signatures applied to coalesced groups of samples, which is beyond the scope of this document.

Typically, a private key would be provisioned to a tamper resistant measurement device at manufacture time. (Any policies or mechanisms for private key reprovisioning or certificate updating are outside the scope of this document). The corresponding public key would be published by the device manufacturer, e.g., on their web page. For each sample, the device would communicate the sample record as well as the signature to an iOS app, which would store both items in the HealthKit database. Note that the private-public key pair is used for digital signing to provide data integrity, not for encryption. The actual values in the data record are in cleartext.

The format used for the digital signature is the CMS (Cryptographic Message Syntax) specified in IETF RFC 5652. The signature is encoded using ASN.1 with DER (Distinguished Encoding Rules). The message digest used should be SHA256, and the signature cipher should be FIPS PUB 186-4 Digital Signature Standard Elliptic Curve P-256. This will ensure both strength and efficiency. In addition, the entire signature should be base64 encoded so that it can be stored in the HealthKit NSString metadata object.

The signature should be of the ASN.1 Signed-data Content Type:

  • SignedData ::= SEQUENCE {
  • version CMSVersion,
  • digestAlgorithms DigestAlgorithmIdentifiers,
  • encapContentInfo EncasulatedContentInfo,
  • signerInfos SignerInfo }

where SignerInfo Type is:

  • SignerInfo ::= SEQUENCE {
  • version CMSVersion,
  • sid SignerIdentifier,
  • digestAlgorithm DigestAlgorithmIdentifier,
  • signatureAlgorithem SignatureAlgorithmIdentifier,
  • signatureSignatureValue }

The digest and signature algorithms are as noted above. Optional items have been left out. The SignerIdentifier is used to retrieve the proper public key for signature verification.

The EncapsulatedContentInfo should be a copy of the relevant items from the sample record generated by the device. This copy should be encoded using ASN.1 DER, and should contain at least a sample timestamp and sample value. The reason the record data is copied inside the signature is in order to have a stable well defined binary encoding (ASN.1 DER) of the data, which is necessary to produce a verifiable signature. A plist structure (key-value pairs) which is ASN.1 encoded should be sufficient for most record types. (See “Encoding plist structures with ASN.1 DER”).

Classes

NSObject

NSObject is the root class of most Objective-C class hierarchies.

HKBiologicalSexObject

This class acts as a wrapper for the HKBiologicalSex enumeration.

HKBloodTypeObject

This class acts as a wrapper for the HKBloodType enumeration.

HKHealthStore

The HealthKit store acts as your link to all the data managed by HealthKit.

HKObject

The HealthKit object is a piece of data that can be stored inside the HealthKit store.The HKObject class is an abstract class.

HKSample

The HealthKit sample represents a piece of data associated with a start and end time.

HKCategorySample

The HKCategorySample class is a concrete subclass of the HKSample class.

HKCorrelation

The HKCorrelation class is a concrete subclass of the HKSample class.

HKQuantitySample

The HKQuantitySample class is a concrete subclass of the HKSample class.

HKWorkout

The HKWorkout class is a concrete subclass of the HKSample class.

HKObjectType

HealthKit uses HKObjectType instances to store type information about data saved in the HealthKit store.

HKCharacteristicType

The HKCharacteristicType class is a concrete subclass of the HKObjectType class.

HKSampleType

The HKSampleType class is an abstract subclass of the HKObjectType class, used to represent data samples.

HKCategoryType

The HKCategoryType class is a concrete subclass of the HKObjectType class.

HKCorrelationType

The HKCorrelationType class is a concrete subclass of the HKObjectType class.

HKQuantityType

The HKQuantityType class is a concrete subclass of the HKObjectType class.

HKWorkoutType

The HKWorkoutType class is a concrete subclass of the HKObjectType class.

HKQuantity

HealthKit uses quantity objects to store numerical data.

HKQuery

The HKQuery class is the basis for all the query objects that retrieve data from the HealthKit store.

HKAnchoredObjectQuery

Anchored object queries provide an easy way to search for new data in the HealthKit store.

HKCorrelationQuery

HealthKit uses correlation queries to search for correlations in the HealthKit store.

HKObserverQuery

Observer queries set up a long-running task on a background queue.

HKSampleQuery

HealthKit uses sample queries to search for sample data in the HealthKit store.

HKSourceQuery

Source queries let you search for the sources (apps and devices) that have saved data to the HealthKit store.

HKStatisticsCollectionQuery

The statistics collection query lets you perform multiple statistics queries over a series of fixed-length time intervals.

HKStatisticsQuery

Statistics queries perform statistical calculations over the set of matching quantity samples.

HKSource

Source objects represents the different data sources in HealthKit.

HKStatistics

Statistics objects represent the result of calculating the minimum, maximum, average, or sum over a set of samples in the HealthKit store.

HKStatisticsCollection

As the name suggests, a statistics collection object manages a collection of statistics.

HKUnit

The unit class manages a wide range of different units for HealthKit.

HKWorkoutEvent

You can use workout events to toggle a workout object between an active and an inactive state.

Other Reference

HealthKit Constants Reference

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值