Developers Club geek daily blog

2 years, 11 months ago
Our colleagues from Techmas will share experience with HealthKit and an application creation for fitness in the scraper of articles. The first article is input on technology and considers the application which selects personal data from Health.

The HealthKit platform was published by the Apple company in iOS 8. It represents API for third-party applications which allows to use to collect information about a state of health of the user. HealthKit includes the Health application preset by default on iOS8 and iOS9 which displays all available data: physical activity, power supply, pressure, calories, time of a dream and other personal characteristics.

Right after start of a platform developers faced a number of problems which led to temporary prohibition on its integration. Now everything is corrected and is debugged, and applications in AppStore with use of HealthKit become more and more.

Work with HealthKit. Part 1

General information

So, HealthKit is the unit with the interface for access to all information:
Work with HealthKit. Part 1
Benefits of its use to application developers:
  • HealthKit serves as the general data storage for a set of applications. For example, for calculation of quantity of steps users can use both different applications, and different devices. At installation of each new application history will remain.
  • Different applications can exchange data with each other without use of additional integration solutions. All information is available in the Health application.
  • HealthKit gives the chance for setup of the separate rights to each application on certain indicators.
  • Expansions of functionality of applications due to use of optional data about health from third-party applications.

Let's note that HealthKit and the Health application are still unavailable to iPad.

It is a little theory

HealthKit represents hierarchy of the unchangeable classes inherited from abstract class of HKObject.

Each object has properties:
  • UUID. Unique record identifier.
  • Source. Data source (there can be both a device, and the application).
  • Metadata. Optional data about record. Provides itself the dictionary containing as predetermined, and the user keys.

Objects in HealthKit can be two types: characteristics (characteristics) and selection (samples). Characteristics represent data which do not change over time: floor, date of birth, blood type. Third-party applications cannot change these data. Selections are available to adding of new data. These are objects of the classes inherited from HKSample. They have the following properties:
  • Type. Selection type: quantity of steps, time of a dream, ave.
  • Start time. Beginning of sampling time.
  • End time. End of time of calculation of selection. If selection in the moment, then value matches the beginning of time.

Example of the application

Below we will consider an application creation which requests use of HealthKit and outputs data on characteristics of the user.

Rights to use HealthKit

HealthKit can use only those applications for which use of HealthKit APIs is the main functionality. For example, the application for an organizer and conducting records will not display data about a state of health. Besides, there is also some other restrictions:
  • Data about health cannot be used in the advertizing purposes. At the same time with HealthKit advertizing blocks can use applications and earn from declarations.
  • The application can share information from HealthKit only with the permission of the user and only with that application which is also authorized and uses HealthKit.

All list of restrictions is available on the website of Apple.

Now we will add HealthKit to the test application. For this purpose, first, we will install the extension for HealthKit in settings of the project.
It is important that App ID has to constrain the line HealthKit, otherwise the option will be unavailable.
Work with HealthKit. Part 1

Further we will add permission of the user to use of data about a state of health.

We import expansion for use of HealthKit:
import HealthKit

Now it is necessary to define object of the class HKHealthStore which is one of the main in HealthKit. HealthKitStore allows to acquire the rights to the HealthKit data access, an opportunity to read out characteristics and to write new selections:
let healthKitStore: HKHealthStore = HKHealthStore()

As we noted earlier, the user selects only separate characteristics to which access has the appendix. All types are descendants of HKObjectType.

Let's create function
 authorizeHealthKit(completion: ((success:Bool, error:NSError!) -> Void)!)

In it we will define data for a read and write.

Given for reading (characteristic):

let healthKitTypesToRead = Set(arrayLiteral:

Given for a read and write (selection):

let healthKitTypesToWrite = Set(arrayLiteral:

Besides, we will add check on use of HKHealthStore on the device (at the moment HealthKit is unavailable on iPad):

if !HKHealthStore.isHealthDataAvailable()
    let error = NSError(domain: "ru.techmas.techmasHealthKit", code: 2, userInfo: [NSLocalizedDescriptionKey:"HealthKit is not available in this Device"])
    if( completion != nil )
        completion(success:false, error:error)

At last, we will request authorization having transferred in parameters two sets with the Set <HKSampleType> and Set <HKObjectType> types for a read and write respectively:

healthKitStore.requestAuthorizationToShareTypes(healthKitTypesToWrite, readTypes: healthKitTypesToRead) {
    (success, error) -> Void in
    if( completion != nil )

Let's add function call to viewDidLoad ():

authorizeHealthKit { (authorized,  error) -> Void in
if authorized {
    print("HealthKit authorization received.")
    print("HealthKit authorization denied!")
    if error != nil {

At an application launch the window will be available:
Work with HealthKit. Part 1

Reading characteristics

The following step we will receive characteristics. Let's add gender and age to the Health application:
Work with HealthKit. Part 1

Let's create the readProfile function (). Its code is given below:

func readProfile() -> (age:NSDate?, bioSex:HKBiologicalSexObject?)
    // Reading Characteristics
    var bioSex : HKBiologicalSexObject?
    var dateOfBirth : NSDate?
    do {
        dateOfBirth = try healthKitStore.dateOfBirth()
        bioSex = try healthKitStore.biologicalSex()
    catch {
    return (dateOfBirth, bioSex)

For access to characteristics we used the created object of healthKitStore.
Possible identifiers and their types for receipt of characteristics accesses to documentation on the link.

Now using the following address we receive a set of characteristics of the user:
let profile = readProfile()

The code of an example is available in git.

In the following articles we will separately describe methods of receipt of selections and adding of data on trainings.

This article is a translation of the original post at
If you have any questions regarding the material covered in the article above, please, contact the original author of the post.
If you have any complaints about this article or you want this article to be deleted, please, drop an email here:

We believe that the knowledge, which is available at the most popular Russian IT blog, should be accessed by everyone, even though it is poorly translated.
Shared knowledge makes the world better.
Best wishes.

comments powered by Disqus