From: http://www.cocoachina.com/ios/20140915/9624.html
This article was translated from Apple's official document by Cocoachina Translation Group members (Weibo): the HealthKit Framework
The HealthKit framework provides a structure that apps can use to share health and fitness data. HealthKit manages data obtained from different sources and automatically merges all data from different sources based on user preferences. The app can also get raw data from each source, and then perform its own data merge. HealthKit can also work directly with health and fitness equipment. In iOS8.0, the system can automatically save data from a compatible, low-power Bluetooth heart rate meter directly in the HealthKit storage. If there is a M7 motion coprocessor, the system can also automatically import step data. Other devices and data sources must have a companion app in order to get the data and save it in HealthKit. HealthKit also provides a health data that should be used to help manage users. The Health app shows users the HealthKit data. Users can use the Health app to view, add, delete, or manage all of their health and fitness data. Users can also edit the sharing permissions for each data type. HealthKit and health apps are not available on ipad. The HealthKit framework cannot be used to apply extensions.
HealthKit and PrivacyBecause health data can be sensitive, HealthKit allows users to control the data by precisely controlling what information is allowed to be read by the application. Users must explicitly set permissions for each app to read and write in the HealthKit store. Users can set permission or deny permissions individually for each type of data. For example, a user can allow your app to read the step data, but it doesn't allow reading of blood sugar levels. To prevent possible disclosure of information, the application is unaware that it is forbidden to read data. From an app's point of view, if you are forbidden to read data, there is no such type of data exists. healthkit data is not saved in icloud and is not synced across multiple devices. This data is only stored on 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 app is not primarily providing health or fitness services, then you can't call HealthKit's API. If your app provides health and fitness services, it must be clearly stated in the sales text and user interface. In particular, the following guidelines apply to all HealthKit applications. 1. your app should not use data collected by HealthKit for advertising or similar services. Note that you might use the HealthKit framework app to serve ads, but you can't use the data in HealthKit to serve ads. 2. You cannot display any data collected by HealthKit to third parties without the express permission of the user. You may only present this data to third parties that provide health or fitness services, even if permitted by the user. 3. You cannot sell data collected by HealthKit to advertising platforms, data agents, or information resellers. 4. If permitted by the user, you can share HealthKit data with third parties for medical research. 5. You must specify how you and your application will use the user's HealthKit data. You must provide a privacy policy for each app that uses the HealthKit framework. You can find guidance on creating a privacy policy on the following Web site: 1. Personal Health Record model (for NON-HIPAA apps): http://www.healthit.gov/policy-researchers-implementers/ Personal-health-record-phr-model-privacy-notice2. HIPAA model (for HIPAA covered apps): http://www.hhs.gov/ocr/privacy/hipaa/modelnotices.html These templates are developed by Onc to explain how user data is collected and shared through straightforward language and approachable design, thereby enhancing user experience and understanding. These are not intended to replace basic Internet privacy policies, and developers should consult Onc to find out which template your app applies to. These templates are for informational purposes only and Apple is not responsible for the consequences of your use of these templates.
Note:This section provides some guidance to help you create a HealthKit app and respect the privacy of your users. It is necessary to understand Apple's requirements for using HealthKit and user health-related data. See the HealthKit section of the app Store Review guidelines to find out more in Apple's app Review support page. For more technical information on using sensitive user data, see the best practices for maintaining user Privacy in APP Programming Guide for IOS.
benefit from Access HealthKitHealth and fitness applications can benefit from access to HealthKit. Some of the major benefits are listed below.
Separation of data collection, processing, and socialization. Modern health and fitness experiences design many different aspects, such as collecting and analyzing data, providing actionable information and useful visual information to users, and allowing users to participate in community discussions. Now it's up to HealthKit to do these things, and you can focus on achieving the areas you're most interested in and handing over other tasks to more specialized applications. The separation of these responsibilities can also benefit users. Each user is free to choose their favorite weight-tracking, step-up, and health challenge apps. This means that the user can choose a set of applications, each of which is well-adapted to the needs of the user. But because these applications are free to exchange data, this entire suite of applications provides a better experience than a single application. For example, some friends decide to take part in a daily pedometer challenge. Everyone can use his preferred hardware device or app to track step data, but they can all use the same social apps to challenge them. Reduce the barriers to sharing between applications. HealthKit makes it easier to share data between applications. For developers, you don't need to download the API and write code to share it with other apps. When new HealthKit apps are available, they automatically start sharing data through HealthKit. This is good for users because they do not need to manually set up app associations or import their data for export. Users still need to set which apps can read and write data from HealthKit, and what data each app can read. Once the user is allowed access, the application can read the data freely and unhindered. Provide richer data and more meaningful content. Applications can read a wider range of data to get a complete view of the user's health and fitness needs. In many cases, an app can modify its unit of measure or hint based on the extra information in HealthKit. For example, a training application can give advice on what to eat after training, depending on the amount of food that the user has already consumed, as well as the type and number of foods he has eaten today. Involve the application in a larger ecosystem. The app benefits by sharing the data it collects using HealthKit. Becoming part of this big ecosystem can help improve the visibility and usability of your application. More importantly, access to HealthKit allows your app and users to work with their favorite apps. If your app doesn't share data with other apps that are already in use, then the user is likely to be looking for another app.
The design idea of HealthKitHealthKit is used to share data in a meaningful way between applications. To achieve this, the framework restricts the use of pre-defined data types and units only. These limitations guarantee that other applications can understand what this data means and how it is used. As a result, developers cannot create custom data types and units. HealthKit, as far as possible, provides a data type and unit that should be complete. The framework also uses a lot of subclasses to create hierarchical relationships among similar classes. Usually there are some subtle but important differences between these classes. There are a lot of related classes that need to be correctly differentiated to work together. For example
HKObject
And
HKObjectType
Abstract classes have many sub-classes of parallel hierarchies. When you use the object and object type, you must make sure that the matching subclasses are used. All objects in the healthkit are subclasses of the hkobject. Most of the HKObject object subclasses are immutable. Each object has the following properties: 1. uuid. Unique identifier for each object. 2. source. The source of the data. The source can be a device that directly deposits data into a HealthKit, or an application. When an object is saved into the HealthKit, HealthKit automatically sets its source. Only the data that is obtained from the HealthKit Source property is available. 3. metadata. A dictionary that contains additional information about the object. The metadata contains pre-defined and custom keys. Predefined keys are used to help share data between apps. The custom key is used to extend the HealthKit object type, adding data for the application to the object. healthkit objects are divided into 2 main categories: Features and samples. A Feature object represents some basic unchanging data. This includes the user's birthday, blood type, and physical sex. Your app cannot save the feature data. The user must enter or modify the data through the Health app. Sample objects represent data at a specific time. All of the sample objects are hksample subclasses. They all have the following properties: 1. type. The sample type. For example, this might include a sleep analysis sample, a height sample, or a step sample. 2. start date. The start time of the sample. 3. end date. The end time of the sample. If the sample represents a moment in time, the end time and start time are the same. If the sample represents data collected over a period of time, the end time should be later than the start time. samples can be subdivided into four sample types. 1. Category samples. This sample represents some data that can be divided into limited categories. In iOS8.0, there is only one category of sample, sleep analysis. For more information, see Hkcategorysample Class Reference. 2. Quantity Sample. This sample represents some data that can be stored as numeric values. The quantity sample is the most common data type in HealthKit. These include the user's height and weight, along with some other data, such as the number of steps to walk, the user's body temperature, and the pulse rate. For more information, seehkquantitysample Class Reference. 3. Correlation. This sample represents composite data and contains one or more samples. In iOS8.0, HealthKit uses correlation to represent food and blood pressure. When creating a bookstore or blood pressure data, you should use correlation. For more information, seehkcorrelation Class Reference. 4. Workout. Workout represents certain physical activities, such as running, swimming, and even games. Workout usually have the properties of type, duration, distance, and energy consumption. You can also associate many detailed samples for a workout. Unlike correlation, these samples are not included in the workout. However, they can be obtained through workout. For more information, seehkworkout Class Reference.
set HealthKitBefore you start using HealthKit, you must perform the following steps: 1. Open the HealthKit feature in Xcode. 2. Call the Ishealthdataavailable method to see if the HealthKit is available on the device. HealthKit is not available on ipad. 3. Instantiate a Hkhealthstore object for your app. Only one HealthKit storage instance is required per application. This storage instance is the primary interface that you interact with the HealthKit database. 4. Use
requestAuthorizationToShareTypes:readTypes:completion:
method to request permission to obtain the HealthKit data. For each type of data, you must request permission to share and read. If the user is allowed to share some kind of data, you can create a new sample of this type and save it in HealthKit. You should use Authorizationstatusfortype: to check whether this type of data is allowed to be shared. If the user is allowed to read some type of data, then you can read the data from the HealthKit. Unfortunately, even knowing that a user refuses to read a certain type of data may indicate a potential health problem. Therefore, your app cannot determine whether the user is allowed to read data. If you don't get permission to read a certain kind of data, it's easy to see that there's no such type of data in HealthKit. For more information about setting up HealthKit, seeHkhealthstore Class Reference. There is an example that shows how to set up and use HealthKit, seeFit:store and Retrieve HealthKit Data.
to add a swatch to the HealthKit storeYour app can create new samples and add them to the HealthKit store. For all sample types, the approximate process is similar, but there are some differences. 1. Inthe correct type identifier was found in the HealthKit Constants Reference. 2. Create a matching Hkobjecttype subclass using the type identifier. There are some handy ways to seehkobjecttype Class Reference. 3. Using the object type, create a matching hksample subclass. 4. Use the Saveobject:withcompletion: method to save the object to the HealthKit store. Each hksample subclass has its own convenient way to instantiate a sample object. The process is as shown. For a quantity sample, you must create an instance of the Hkquantity class. The units of quantity must be related to the available units as described in the type identifier document. For example, the Hkquantitytypeidentifierheight document indicates that it uses length units, so your number must be in centimeters, meters, feet, inches, or other length units. For more information, seehkquantitysample Class Reference. For a class sample, its value must be related to the enumeration value described in the type identifier document. For example, the Hkcategorytypeidentifiersleepanalysis document indicates that it uses the Hkcategoryvaluesleepanalysis enumeration value. So you must pass a value from this enumeration when you create the sample. For more information, seehkcategorysample Class Reference. For correlation, you must first create all the samples contained in the correlation. The type identifier of the correlation describes the types and number of objects it can contain. Do not deposit the contained object into the HealthKit. They are stored as part of the correlation. For more information, seehkcorrelation Class Reference. Workout and other types of samples are somewhat different. First, creating an Hkworkouttype instance does not require specifying a type identifier. All workout are used with the same type identifier. Second, you need to provide a Hkworkoutactivitytype value for each workout. This value defines the type of activity that is performed in workout. Finally, when workout is saved to HealthKit, you can associate additional samples with workout. These samples provide detailed information on the workout. For more information, seehkworkout Class Reference.
reading HealthKit dataHealthKit provides a number of ways to read data. 1. Direct method invocation. HealthKit provides a way to read feature data directly. These methods can only be used to read feature data. For more information, see Hkhealthstore Class Reference. 2. Sample queries. This is the most used query. Use a sample query to read any type of sample data. Sample queries are especially useful when you want to sort the results or limit the total number of samples that are returned. For more information, see hksamplequery Class Reference. 3. Observer queries. This is a long-running query that detects HealthKit storage and notifies you when a matching sample has changed. If you want to be notified when storage changes, use observer queries. You can have these queries executed in the background. For more information, see Hkobserverquery Class Reference. 4. Anchor object query. Use this query to search for items added to the store. When the anchor query executes for the first time, all matching samples in the store are returned. In the next execution, only the items that were added after the last execution are returned. Typically, anchored object queries are used with observer queries. The Observer query tells you that some items have changed and anchored object queries to determine what (if any) items were added to the store. For more information, see Hkanchoredobjectquery Class Reference. 5. Statistical queries. Use this query to perform statistical operations in a series of matched samples. You can use statistical queries to calculate the sum, minimum, maximum, or average of a sample. For more information, see hkstatisticsquery Class Reference. 6. Statistics collection query. Use this query to perform multiple statistical queries in a series of fixed-length intervals. Typically, this query is used to generate a chart. Queries provide some simple ways to calculate certain values, such as the total calories consumed per day or the number of steps to walk every 5 minutes. Statistical collection queries are long-running. Queries can return the current collection of statistics, or they can monitor HealthKit storage and respond to updates. For more information, see Hkstatisticscollectionquery Class Reference. 7. correlation query. Use this query to find data in correlation. This query can be a correlatioEach sample type in n contains a separate predicate. If you just want to match the correlation type, then use the sample query. For more information, see hkcorrelation Class Reference. 8. Source query. Use this query to find the source of matching data (apps and devices) in the HealthKit store. The source query lists all the sources of a specific sample type that is stored. For more information, see Hksourcequery Class Reference.
Unit ConversionsHealthKit uses Hkunit and hkquantity classes to support units. The Hkunit provides a single unit representation. It supports most of the metric and imperial units and, of course, the basic unit and conforming units. The base unit represents a single metric, such as meters, pounds, or seconds. A composite unit uses mathematical operations to connect one or more basic units, such as M/s or lb/ft2. Hkunit provides a convenient way to create all the basic units supported by HealthKit. It also provides the mathematical operations needed to build a composite unit. Finally, you can also create a composite unit by directly using the appropriate formatted unit string. For more information, see Hkunit Class Reference. The Hkquantity class stores the values for a given unit. You can then use any compatible unit to take the value. In this way, your application can easily complete the unit conversion. For more information, see Hkquantity Class Reference. In some cases, you can use the formatter to localize the quantity. IOS8 provides a new formatter to handle length (nslengthformatter), Mass (nsmassformatter), and Energy (nsenergyformatter). For the other quantities, you need to convert the units and localize the data yourself.
MultithreadingHealthKit storage is thread-safe, and most HealthKit objects are immutable. In general, you can safely use HealthKit in a multithreaded environment.
Note:All completion callbacks for the HealthKit API are executed in a private background queue. So before you update the user interface or modify some of the resources that can only be processed in the main thread, you should pass the data back to the main thread. For more information on multithreading and concurrent programming, see Concurrency Programming Guide.
Add a digital signatureThe digital signature metadata object in HealthKit provides the data integrity of the sample records generated by the trusted device. A metadata item stores a copy of a digitally signed sample record. The signature is generated by the device (because the device stores a private signing key, the device should be tamper-proof). This allows the user of the data to check the signature through the public key of the device, thereby verifying that the record data has been modified. Since each record is individually signed, it can store a total of approximately 1K bytes of signatures per record. Therefore, this metadata signature entry is used for records that have a sample rate of up to several times per day. A higher sample rate requires that the sample group be signed, which is beyond the scope of this document. Typically, the private key is placed in a tamper-proof measurement device at manufacture time. (The policy or mechanism for a private key reset or certificate update is not in the scope of this document) The associated public key is published by the device manufacturer, for example, on their website. The device should pass the sample data and signatures of each sample to the iOS app, both of which are stored in the HealthKit database. Note that the public private key of a digital signature is used to provide data integrity checks, not for encryption. The actual value in the data record is clear text. The format of the digital signature is the CMS (cryptographic Message Syntax) in IETF RFC 5652. The signature is encoded using ASN.1 der (Distinguished Encoding Rules). The information digest used should be SHA256, and the signature encryption should be FIPS PUB 186-4 Digital Signature standard Elliptic Curve P-256. This is guaranteed in length and efficiency. In addition, the entire signature should be BSAE64 encoded so that it can be stored in the HealthKit nsstring metadata object. The signature should be ASN.1 signed-data Content Type:
- Signeddata:: = SEQUENCE {
- Version cmsversion,
- Digestalgorithms Digestalgorithmidentifiers,
- Encapcontentinfo Encasulatedcontentinfo,
- Signerinfos SignerInfo}
SignerInfo type is:
- SignerInfo:: = SEQUENCE {
- Version cmsversion,
- Sid Signeridentifier,
- Digestalgorithm Digestalgorithmidentifier,
- Signaturealgorithem Signaturealgorithmidentifier,
- Signaturesignaturevalue}
The above is the abstract and signature algorithm. None of the optional items are included. The signeridentifier is used to obtain the appropriate public key to validate the signature. Encapsulatedcontentinfo is a copy of the related item from the sample record generated by the device. The copy should be encoded with ASN.1 der and should contain at least one sample timestamp and sample value. The recording data is copied into the signature in order to have a stable, well-defined binary encoding (ASN.1 DER), which is necessary to generate a verifiable signature. ASN.1 encoded PLIST structure (key-value pairs), should be able to satisfy most of the record types. (see "Using ASN.1 der to encode the plist structure")
HealthKit frame Reference (RPM)