Apple HealthKit

Multiple updates have arrived to Apple devices with iOS 8, some of them regarding health. Currently, these updates have more relevance with Apple Watch.

Health app was one of these updates; it centralizes user health data and fitness data. It shows data from the device internal sensors and from third applications which store fitness data from users. It provides a dashboard where it is possible to access, at one time, all monitorized information, also historics, charts or summaries that are available, and an emergency card accessible from the lock screen.

Other important release for iOS developers, is the new health framework: Apple HealthKit. With this service, health and fitness apps are able to share data in a secure way, with user authorization.

Some health projects at Solid GEAR have used HealthKit framework.

At the beginning, we need a provisioning profile for the app which supports HealthKit and it is necessary to activate it in the Capabilities section in the target.

Config Health Kit

Once the framework is added to the Xcode project, we can use it.

HealthKit use HKObjectType objects to store information. However, it is not possible to use these objects, instead we are going to use subclasses which are: HKCharacteristicType and HKSampleType.

HKCharacteristicType class stores data that is not going to change anymore. This data need to be set and to be edited directly into the Health app, it is not going to be modified from third applications, it is only possible to consume it. They are: Biological sex, blood type and birth date.

HKSampleType class represents sample data and has several subclasses: HKCategoryType, HKCorrelationType, HKQuantityType and HKWorkoutType.

  • HKCategoryType: Use it to store an enumeration of values. Only use it to store sleep analysis data.
  • HKCorrelationType: To work with correlations, objects who store several samples in a single data input.
  • HKQuantityType: To store samples with a single numeric value.
  • HKWorkoutType: Use it to create a workout from workout object queries.

To start using HealthKit, we need to get user authorization.

The following image shows an authorization view, where you choose the data which other apps can read and write. You have to select each category individually.

Authorization view healthkit

We need to initialize a HKHealthStore object in our code:

var healthStore = HKHealthStore()

Next, we are going to request user authorization:

self.healthStore.requestAuthorizationToShareTypes(typesToShare as Set, typesToRead: readDataType as Set, completion: { (success: Bool, error: NSError!) -> Void in
       println("Success: \(success)")
       println("Error: \(error)")
   })

Where typesToShare is a NSSet object which stores data types to write in HealthKit, and typesToRead is a NSSet object which stores data types to read from HealthKit.

If we want to get a fix data (HKCharacteristicType) as blood type, it is necessary to create a NSSet from HKCharacteristicType with the correct identifier for blood type, HKCharacteristicTypeIdentifierBloodType:

let bloodCharacteristicType: HKCharacteristicType = HKObjectType.characteristicTypeForIdentifier("HKCharacteristicTypeIdentifierBloodType")
var typesToRead: NSMutableSet = NSMutableSet(object: bloodCharacteristicType)

Also, if we want to get user birth date, we need to add other data to typesToShare :

let dateOfBirthCharacteristicType: HKCharacteristicType = HKObjectType.characteristicTypeForIdentifier("HKCharacteristicTypeIdentifierDateOfBirth")
typesToRead.addObject(dateOfBirthCharacteristicType)

Once we obtain user authorization, interaction with HealthKit is possible. To get blood type:

let error: NSError?
let bloodType: HKBloodTypeObject = self.healthStore.bloodTypeWithError(&error)!

HKBloodTypeObject has a bloodType property, who could be:
HKBloodTypeNotSet, HKBloodTypeAPositive, HKBloodTypeANegative, HKBloodTypeBPositive, HKBloodTypeBNegative, HKBloodTypeABPositive, HKBloodTypeABNegative, HKBloodTypeOPositive or HKBloodTypeONegative.

To get birth date:

let error: NSError?
let dateOfBirth: NSDate = self.healthStore.dateOfBirthWithError(&error)!

We may want to get data as: body mass, height or heart rate. For being able to get them we need to complete typesToRead:

let bodyMassQuantityType: HKQuantityType = HKObjectType.quantityTypeForIdentifier("HKQuantityTypeIdentifierBodyMass")
let heightQuantityType: HKQuantityType = HKObjectType.quantityTypeForIdentifier("HKQuantityTypeIdentifierHeight")
let heartRateQuantityType: HKQuantityType = HKObjectType.quantityTypeForIdentifier("HKQuantityTypeIdentifierHeartRate")
typesToRead.addObjectsFromArray([bodyMassQuantityType, heightQuantityType, heartRateQuantityType])

To get quantity data there are several options, but we are going to get the latest one, so we create a query:

let quantityType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)
    let timeSortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
    let query = HKSampleQuery(sampleType: quantityType, predicate: nil, limit: 1, sortDescriptors: [timeSortDescriptor]) { (query, results, error) -> Void in
       var quantitySample: HKQuantitySample = NSArray(array: results).firstObject as! HKQuantitySample
       var quantity: HKQuantity = quantitySample.quantity
    }
    self.healthStore.executeQuery(query) 

Quantity is the searched value. This quantity could be shown in different units.

Here a list with International System of Units:

Unit string Name Type
“g” Grams Mass
“m” Meters Length
L” or “l” Liters Volume
“Pa” Pascals Pressure
“s” Seconds Time
“J” Joules Energy
“K” Kelvin Temperature
“S” Siemens Electrical conductance
“mol” molar mass Moles Mass

Each of these units needs to include a prefix, but it is also possible to use non-SI units, too.
More information: HealthKit Framework Reference.

These are some advices to start using HealthKit, but there are a lot of possibilities.

Furthermore, in Solid GEAR we have created a health module.

With this module and a plist where the type of data we want to read and write is stored, we are able to use HealthKit easily in each of our apps.

Now, it is your turn! Use HealthKit to improve your iOS apps! 

Leave a Comment

¿Necesitas una estimación?

Calcula ahora