How to Integrate Apple's HealthKit

As seen in the number of movement-tracking devices around people's wrists, fitness is big these days. It's also big business, with big companies making big investments in the space. One of those companies is Apple, whose HealthKit received a significant amount of attention at the Apple Worldwide Developers Conference.

To take on the increasingly crowded space — comprising health apps such as RunKeeper and Nike+ and tracking gadgets such as Fitbit, all vying for mind and market space through development SDKs and gadgets for the consumers — Apple has released the HealthKit SDK. This Platform will give developers the ability to integrate and centralize their existing health-focused app data — from running and cycling stats to food and medicine consumption, and much more.

Of course, the HealthKit SDK isn't the only thing Apple has rolled out recently, and its new hardware and software offerings all have a health angle. Its new line of iPhones, for example, has a dedicated CPU capable of tracking steps efficiently, and the Apple Watch, slated for release in early 2015, is all about health, designed to, among other things, read users' heartbeat intervals through wrist-facing sensors.

It's going to be a competitive space, to say the least, with none other than Google also releasing a health SDK and its own line of wearables.

What Are the Benefits of HealthKit?

HealthKit offers a number of important benefits. Users get a centralized dashboard — gorgeous and customizable — containing all their health data. Importantly, the data can be aggregated from many different health apps, which means users don't have to use one app for tracking nutrition, one for tracking exercise, one for tracking heart rate and so on. All of their measurements can be aggregated in and accessed from one place.

Developers likewise benefit from this centralization: They can focus on a core health feature and have it included in the centralized Apple Health dashboard and shared with other apps.

Another benefit for developers is the distinct separation of data collection and processing — complicated processes such as unit conversions and graphing — allowing developers to focus on more purposeful and strategic work that will ultimately differentiate their app value proposition. Developers leverage the iOS platform by sharing and pooling health measurements, along with the other participating apps, to provide a centralized repository of data that can be queried and visualized through charts, for example.

Consumers can choose which app they want to use for each Function — for example, calorie tracking, step counting, and stat and information sharing. Developers therefore gain a distinct separation of labor and logic, of data collection and processing — a Decoupling that allows for greater focus and development of their core competencies.

Eventually, an ecosystem will be built around HealthKit. You won't necessarily need to use custom, vendor-specific APIs to share data with apps such as RunKeeper or MyFitnessPal. Instead, you would use the HealthKit store as a conduit for interapp information sharing.

Having noted the benefits to both consumers and developers, let’s dive into setting up HealthKit on an existing or new Xcode project.

HealthKit SDK Overview

In HealthKit, you work with sets of objects (or samples) of type HKObjectType, but more commonly a more subclassed-specific characteristic variant, such as HKCharacteristicType or HKSampleType. The following is the complete list of HealthKit SDK classes, according to Apple Development.





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


This class acts as a wrapper for the HKBiologicalSex enumeration.


This class acts as a wrapper for the HKBloodType enumeration.


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


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


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


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


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


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


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


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


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


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


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


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


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


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


HealthKit uses quantity objects to store numerical data.


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


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


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


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


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


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


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


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


Source objects represent the different data sources in HealthKit.


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


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


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


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

Depending on the sample type you are interested in, the sample would fall into one of these types, requiring separate explicit permission for:

  • Quantity samples: Samples that can be specified numerically, like weight, height or glucose index; quantity types fall into either discreet values (noncumulative, such as weight) or cumulative values (that is, calories per day).
  • Category samples: Samples that are not numerically categorized, but rather categorize a finite set of categories. Currently, only sleep analysis falls into this category.
  • Correlation samples: You can correlate samples of this type with other values, like blood pressure correlating to heart rate.
  • Characteristic samples: Samples like date of birth, which is a user trait that is not quantifiable.
  • Workouts: Measuring some sort of physical activity, such as running or cycling or swimming, that contains measurement properties, such as distance, duration and energy burned, and is part of the HKWorkout Class.

You work with quantity samples by declaring them as follows:

let weightQty = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)
let heightQty = HKQuantityType.quantityTypeForIdentifier(

We would then signal that we were interested in sharing weight quantity sample, by declaring the following:


lazy var toShareTypes: NSSet = {
return NSSet(objects: self.weightQty)


To request read permissions for weight, we would declare:


lazy var readTypes: NSSet = {
return NSSet(objects: self.weightQuantity,...)  

Assuming that we were able to access health data, we would then request authorization to share the quantity sample weight, as well as access to read, as follows:

if HKHealthStore.isHealthDataAvailable(){

    readTypes: readTypes,
    completion: {(succeeded: Bool, error: NSError!) in
      if succeeded && error == nil{
        println("Successfully received authorization")”


When the sequence above runs, the user will get a prompt asking specifically and explicitly which data the app has permission to read and share. This allows the user to toggle each quantity property individually. The completion handler will then return the results and determine whether the statistics the user has permitted are sufficient for the app to function as needed.

Working With HealthStore

We will show a quick demonstration on how to contribute (or write) new sample data to HealthStore, as well as how to read pooled data.

Contributing samples to the store, you would implement an HKObjectType subclass type and matching constant identifier, along with the relevant HKSample subclass, via the object type. You finally save the object using saveObject:withCompletion: method block.


let kgUnit = HKUnit.gramUnitWithMetricPrefix(.Kilo)
let weightQty =  HKQuantity(unit: kgUnit,
doubleValue: self.weightValue)

let sample = HKQuantitySample(type: weightQty,
quantity: weightQty,
startDate: NSDate(),
endDate: NSDate() )

store.saveObject(sample, withCompletion: {
(succeeded: Bool, error: NSError!) in


All of this is quite straightforward, and the process of consuming/reading sample data follows a pattern similar to working with CoreData — using predicates and sort descriptors, and, finally, by calling the query in the last line, using store.executeQuery(query):


let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate,
ascending: false)

let query = HKSampleQuery(sampleType: weightQtyType, predicate: nil,
limit: 1, sortDescriptors: [sortDescriptor],
resultsHandler: {[weak self] (query: HKSampleQuery!, resultsBack: [AnyObject]!,
  error: NSError!) in
     if resultsBack > 0{
            let sampleResult = resultsBack[0] as HKQuantitySample
        let weight = sampleResult.quantity.doubleValueForUnit(

         let formatter = NSMassFormatter()
         let kilogramSuffix = formatter.unitStringFromValue(weight,
      unit: .Kilogram)
        dispatch_async(dispatch_get_main_queue(), {
            let strongSelf = self!





HealthKit is probably the most prominent of the three major SDKs Apple released this summer. Along with the new iPhones and Apple Watch, which is slated for release early next year, Apple is pushing heavily to be the hardware provider for a more health-conscious world. 

Apple’s SDK provides tangible benefits to consumers, who tend to use multiple apps to track and measure different health properties (from running to calorie consumption). Apple wants to offer a centralized platform on which disparate health information can be collected and organized into a presentable dashboard. 

Developers gain the benefit of data collection separation, allowing them to focus on their core health features while leveraging existing pooled data from HealthStore. Developers also avoid having to deal with complicated unit measurement conversions, working with discreet and cumulative samples, implemented differently by third-party SDKs. 

The real potential for developers will come when they get their hands on the Apple Watch and can put it into action with innovative ideas for wearable tech. Indeed, this is certainly an exciting period for health and health-related apps, and with heavyweights Apple and Google putting significant resources into this space, we will also likely see larger market opportunities. 

Further Reading

Following are resources to aid you in getting you started with HealthKit:

Be sure to read the next Health article: How APIs Will Enable Better Self-Management of Health