iOS Iphone Developer Swift

HealthKit for iOS8: Part 2

So you got past the intro and learned about the health store and how we need authorization from the user in order to have read and write access to certain properties.  Now that the user trusts your app, let’s learn how to interact with the health store.

1. HKObjects and the health store

Before we get into reading and writing, let’s get to know HKObjects.  Here is the class tree:

HealthKit HKObject Hierarchy
HealthKit HKObject Hierarchy

As you can see, HKObjectType inherits directly from NSObject.  You can basically have 2 types of HKObjects; HKCharacteristic and HKSample -Type.  HKCharacteristicType doesn’t change over time whereas HKSampleType does change, such as calories consumed, calories burnt, Glucose levels etc.  Let’s see some examples:

HKCharactersiticType has 3 main objects:

Biological Sex

Blood Type


HKSampleType has objects like:

-HKCategoryType: discrete, finite values that can be enumerated such as sleep analysis.

-HKCorrelationType: for creating correlated objects grouped as one.

-HKQuantityType: used for creating objects that store numerical values.

-HKWorkoutType: used for creating workout objects.

-FURTHERMORE: HKSample has HKCategorySample & HKQuantitySample

For the most part you will simply fetch HKCharacteristic types from the health store of the user.  The user will have input those values through his/her Health app.  HKSample types on the other hand you will read and write constantly.  Let’s think about how we need to write data:

A. Decide on a Type Identifier

B. Create a matching HKObjectType

C. Create an HKSample

D. Call saveObject on the health store

Let’s take a look at saving data:

self.healthStore?.saveObject(calorieSample, withCompletion: { (success, error) in
// do a bunch of UI stuff probably in the main queue

Ok so you might be thinking, what kinds of objects are involved here.  What is dateOfBirth or calorieSample?  Well the best way of understanding is to see an example.  Here are images representing the logic behind writing data to the store.  As mentioned earlier, you find a matching type, set it, create a sample for it and saveObject!  This is the process for a Category type:

HealthKit iOS8 HKCategory by
HealthKit iOS8 HKCategory

We need to find the matching identifier for the category type in order to save a Category Sample.  Likewise for the Quantity type:

HealthKit iOS8 HKQuantity by
HealthKit iOS8 HKQuantity

What this means is that before you call saveObject and pass it in that calorieSample, you need to have properly defined calorieSample:


var quantityType: HKQuantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryEnergyConsumed)


var quantity: HKQuantity = HKQuantity(unit: HKUnit.jouleUnit(), doubleValue:300)


var now: NSDate = NSDate()

var metadata: NSDictionary = ["HKMetadataKeyFoodType":"Ham Sandwich"]


var calorieSample: HKQuantitySample = HKQuantitySample(type: quantityType, quantity:quantity, startDate:now, endDate:now, metadata:metadata)

Finally you can call the saveObject method.  That’s not so bad.  So you would do the same for energy burnt in a workout, calcium intake, etc.

Now let’s take a look at how we would read data from the store:

func fetchUsersAge () -> () {

var error: NSError?

var dateOfBirth = self.healthStore?.dateOfBirthWithError(&error)

if error != nil {

NSLog("An error occured fetching the user's age information. In your app, try to handle this gracefully. The error was: \(error)")

//Present VC




As you can see, this is quite simple, we basically say self.healthStore?.dateOfBirthWithError.
Now dateOfBirth is not only a finite, or discrete measure but its also a Characteristic type, it doesn’t change with time.  How would you read other data, HKSampleTypes such as height and weight or Dietary Calories which are not discrete, in other words not whole numbers but infinitesimally scalar and change constantly?  That’s what HKQuery is for!

2. Queries & Stats

Sometimes you want to be able to query the health store for data, that’s what HKQuery is for.  If it’s a quantity sample type then we probably want to save the start and end date with it as before.  So here is an example of how to query our health store:

// 1. Create a date

var now: NSDate = NSDate()

let calendar : NSCalendar = NSCalendar.currentCalendar()

var components: NSDateComponents = calendar.components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay, fromDate: now)

var startDate: NSDate = calendar.dateFromComponents(components)!

var endDate: NSDate = calendar.dateByAddingUnit(.CalendarUnitDay, value:1, toDate:startDate, options:nil)!

// 2. Create the identifier

var sampleType: HKSampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryEnergyConsumed)

// 3. Create the predicate to search with

var predicate: NSPredicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate:endDate, options:.None)

// 4. Create the HKSampleQuery because we are querying sample types

var query: HKSampleQuery = HKSampleQuery(sampleType: sampleType, predicate: predicate, limit: 0, sortDescriptors: nil) { (query:HKSampleQuery?, results:[AnyObject]!, error:NSError!) -> Void in

if (error != nil) {

NSLog("An error occured fetching the user's tracked food. In your app, try to handle this gracefully. The error was: %@.", error)



if results != nil {

NSLog("Got something!")


// do UI stuff probably in the main queue

self.healthStore?.executeQuery(query)     // EXECUTE QUERY


3. User input UI

So let’s start creating an app.  As you can see, this is all based on the sample app from Apple called Fit.  But it has been modified to add some workout data.  What we want is to be able to read data from our health store (which will provide us with a user’s profile view), collect some user info on how much energy was consumed (which will give us our Energy Consumption view) and have the user input their workout info which in our case is going to be a swimming app (this will give us a Workout view).  For the last 2 data, we will write to the health store how much energy we consumed and how much we burnt.

Ok so we have our AppDelegate and Storyboard.  To recap, you’ve activated the HealthKit capabilities in your project which if you go to the Dev Center, Xcode has created a Team provisioning profile for this app you created and its enabled for HealthKit.  This also gave you an Entitlements file in your navigator which looks like this:

HealthKit app iOS8 by
HealthKit app iOS8

The Journal file is something I create to keep track of my work, ignore that.  The FoodItem is a file we will quickly throw up on the screen but is a simple Custom Class file to be used in the UI part of this app.  For the first part which deals with the Profile view controller we won’t concern ourselves with it.

Ok so let’s take a quick look at our Profile view controller class.  As always we start out with our properties:

class ProfileViewController: UITableViewController, UITextFieldDelegate {
@IBOutlet var ageValueLabel: UITextField!
@IBOutlet var ageUnitLabel: UILabel?
@IBOutlet var heightValueTextField: UITextField!
@IBOutlet var heightUnitLabel: UILabel?
@IBOutlet var weightValueTextField: UITextField!
@IBOutlet var weightUnitLabel: UILabel?
var healthStore: HKHealthStore?

We have created 6 IBOutlet’s.  Each UILabel will hold unit values and each corresponding UITextField will hold the respective data we fetch from the health store.

Then we create a variable for our HealthStore which, if you recall, is set for us from our AppDelegate once it receives authorization.

Now our methods:

Each time our view will appear, we want to update our data, since it may have changed:

override func viewWillAppear(animated: Bool) {
// Update the user interface based on the current user's health information.

Ok so with each viewWillAppear, we call methods to update our UI with the latest data from our store, which of course means we will fetch from the store and as you recall, it was different fetching a CharacteristicType such as DOB vs a Sample Type such as weight.  So let’s take a look at the simplest one first:

func updateUsersAge () -> () {

var error: NSError?

var dateOfBirth = self.healthStore?.dateOfBirthWithError(&error)

if error != nil {

NSLog("An error occured fetching the user's age information. In your app, try to handle this gracefully. The error was: \(error)")



if dateOfBirth != nil {

NSLog("Found a DOB \(dateOfBirth)")


if dateOfBirth == nil {

var dateFormatter = NSDateFormatter()

dateFormatter.dateFormat = "yyyy-MM-dd"

dateOfBirth = dateFormatter.dateFromString("1974-10-18")!


// Compute the age of the user.

let now: NSDate = NSDate()

let calendar : NSCalendar = NSCalendar.currentCalendar()

var ageComponents = calendar.components(.CalendarUnitYear,

fromDate: dateOfBirth!,

toDate: now,


var usersAge: Int = ageComponents.year

var ageValueString: NSString = NSNumberFormatter.localizedStringFromNumber(usersAge, numberStyle:NSNumberFormatterStyle.NoStyle)

if let something = self.ageValueLabel!.text {

self.ageValueLabel!.text = ageValueString



Ok so first we simply fetch the value for dateOfBirth from our store and if we get an error back, we log it.  If dateOfBirth is not nil, then we log success.  You will see a strange bit now, where it checks whether if DOB is nil.  I know, we already checked if error was nil, so DOB should not be nil, but sometimes its empty.  The user may not have set DOB on his or her device yet.  This means you will get nil and your app will crash.  So in case DOB IS nil, we hard code one.  Finally we compute the user’s age based on their DOB by using NSDateComponents and we assign the computed Int to our label using NSNumberFormatter.localizedStringFromNumber method.

Now let’s see how to get height and weight, which are Sample types:

func updateUsersHeight () -> () {

// Fetch user's default height unit in inches.

var lengthFormatter: NSLengthFormatter = NSLengthFormatter()

lengthFormatter.unitStyle = NSFormattingUnitStyle.Long

var heightFormatterUnit: NSLengthFormatterUnit = NSLengthFormatterUnit.Inch

self.heightUnitLabel!.text = lengthFormatter.unitStringFromValue(10, unit:heightFormatterUnit)

var heightType: HKQuantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)

self.fetchMostRecentDataOfQuantityType(heightType, withCompletion: { (mostRecentQuantity:HKQuantity?, error:NSError?) -> () in

//some code

if let something = error {

NSLog("An error occured fetching the user's height information. In your app, try to handle this gracefully. The error was: %@.", something)



//Determine the height in the required unit.

var usersHeight: Double = 0.0

if let somethingElse = mostRecentQuantity {

var heightUnit: HKUnit = HKUnit.inchUnit()

usersHeight = mostRecentQuantity!.doubleValueForUnit(heightUnit)

// Update the user interface.

dispatch_async(dispatch_get_main_queue(), {

self.heightValueTextField.text = NSNumberFormatter.localizedStringFromNumber(usersHeight, numberStyle:.NoStyle)





Ok so we use NSLengthFormatter to determine the length style to use.  Then we use its NSLengthFormatterUnit in order to specify the unit in order to set the label for the height value.  Now we get into fetching requirements, so we must create the matching type first and then pass it into our fetch method which is called fetchMostRecentDataOfQuantityType.  So we are passing our quantity type of height, to this method.  We will study that method in a bit, but for the time being, notice we pass in a completion handler.  If that completion handler receives an error, it will log the error.  Otherwise, we create a variable for height, use the received mostRecentQuantity variable and test it since its an optional, create a heightUnit from HKUnit and unwrap the mostRecentQuantity value into our usersHeight variable using our heightUnit.

What?  Double take!  Ok, here we go, this time with weight:

func updateUsersWeight () -> (){

// Fetch the user's default weight unit in pounds.

var massFormatter: NSMassFormatter = NSMassFormatter()

massFormatter.unitStyle = NSFormattingUnitStyle.Long

var weightFormatterUnit: NSMassFormatterUnit = NSMassFormatterUnit.Pound

self.weightUnitLabel!.text = massFormatter.unitStringFromValue(10, unit:weightFormatterUnit)

// Query to get the user's latest weight, if it exists.

var weightType: HKQuantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)

self.fetchMostRecentDataOfQuantityType(weightType, withCompletion: { (mostRecentQuantity: HKQuantity?, error: NSError?) -> () in

if ((error) != nil) {

NSLog("An error occured fetching the user's weight information. In your app, try to handle this gracefully. The error was: %@.", error!);



// Determine the weight in the required unit.

var usersWeight:Double = 0.0

if let somethingArse = mostRecentQuantity {

var weightUnit: HKUnit = HKUnit.poundUnit()

usersWeight = mostRecentQuantity!.doubleValueForUnit(weightUnit)

// Update the user interface.

dispatch_async(dispatch_get_main_queue(), {

self.weightValueTextField.text = NSNumberFormatter.localizedStringFromNumber(usersWeight, numberStyle:.NoStyle)





Again, we use NSMassFormatter for our style, its NSMassFormatterUnit for our unit, create the weight type identifier and pass it in to our fetch method along with a completion handler.  If the completion handler returns error, we log it.  Otherwise, we create a local variable to store the usersWeight, if let check mostRecentQuantity because its an optional and use it to assign its doubleValue using weightUnit to our local usersWeight variable.  Finally we update the UI in the main queue as always.

Ok so let’s take a look at this magical method, fetch something or other:

func fetchMostRecentDataOfQuantityType(quantityType: HKQuantityType, withCompletion completion: ((mostRecentQuantity:HKQuantity?, error:NSError?) -> ())? ) {

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

let query = HKSampleQuery(sampleType: quantityType, predicate: nil, limit: 1, sortDescriptors: [timeSortDescriptor]) { query, results, error in

if completion != nil && error != nil {

completion!(mostRecentQuantity: nil, error: error)



let resultsArray = results as NSArray?

var quantitySample: HKQuantitySample? = resultsArray?.firstObject as HKQuantitySample?

var quantity: HKQuantity? = quantitySample?.quantity

if completion != nil {

completion!(mostRecentQuantity: quantity, error: error)





Ok, not that complicated really.  We create a NSSortDescriptor in order to arrange our results and be able to get the latest one.  We create the HKQuery and pass it in the sampleType (height or weight, depending on what was passed into the fetch method), limit results to 1 and no predicate.  We pass in the sort descriptor and another completion handler.  Here are the cases tested next:

– If the HKQuery completion handler is NOT nil && the error is also NOT nil, then there is an error, so return the other completion handler with nil

– Otherwise, take the results AnyObject from the HKQuery and cast it as NSArray, get its firstObject as HKQuantitySample, get its quantity and set it to some local variable called quantity.  Then again check if the original completion is NOT nil, then return the original completion handler with the quantity results.  Finally execute the query!

Finally, you may have noticed the user can update their height and weight.  And we adopted the UITextFieldDelegate protocol for that.  So let’s:

func textFieldShouldReturn (textField: UITextField) -> (ObjCBool) {


if textField == self.heightValueTextField {


} else if textField == self.weightValueTextField {



return true;


call save each time the user modifies their height or weight.  And those methods are simply:

func saveHeightIntoHealthStore () -> () {

var formatter: NSNumberFormatter = self.numberFormatter()

var height: NSNumber?

if let somethingA = self.heightValueTextField!.text {

height = formatter.numberFromString(self.heightValueTextField!.text)


let cosa:NSNumber = 8

var otra = cosa.doubleValue

if height == height {

// Save the user's height into HealthKit.

var heightType: HKQuantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)

var heightQuantity: HKQuantity = HKQuantity(unit:HKUnit.inchUnit(), doubleValue: height!.doubleValue)

var heightSample: HKQuantitySample = HKQuantitySample(type: heightType, quantity:heightQuantity, startDate:NSDate(), endDate:NSDate())

self.healthStore?.saveObject(heightSample, withCompletion: { (success, error) in

if (!success) {

NSLog("An error occured saving the height sample %@. In your app, try to handle this gracefully. The error was: %@.", heightSample, error)






Format the value, carefully unwrap the textfield value, create a new height type identifier, height quantity and height sample and save it to the health store.  Likewise for the weight:

func saveWeightIntoHealthStore () -> () {

var formatter: NSNumberFormatter = self.numberFormatter()

var weight: NSNumber?

if let somethingIsInsideOf = self.weightValueTextField!.text {

weight = formatter.numberFromString(self.weightValueTextField!.text)!

NSLog("The weight entered is not numeric. In your app, try to handle this gracefully.");



if weight == weight {

// Save the user's weight into HealthKit.

var weightType: HKQuantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)

var weightQuantity: HKQuantity = HKQuantity(unit: HKUnit.inchUnit(), doubleValue: weight!.doubleValue)

var weightSample: HKQuantitySample  = HKQuantitySample(type:weightType, quantity:weightQuantity, startDate:NSDate(), endDate:NSDate())

self.healthStore?.saveObject(weightSample, withCompletion: { (success, error) in

if (!success) {

NSLog("An error occured saving the weight sample %@. In your app, try to handle this gracefully. The error was: %@.", weightSample, error)






And we need the number formatter method:

func numberFormatter ()->(NSNumberFormatter) {

var numberFormatter: NSNumberFormatter?

dispatch_once(&onceToken, {

numberFormatter = NSNumberFormatter()


return numberFormatter!


Since we use this onceToken, we need to define it globally at the top of the class by adding this line below the following imports:

import UIKit
import HealthKit
var onceToken: dispatch_once_t = 0

See you in Part 3!

iOS Iphone Developer Swift

HealthKit for iOS8: Part 1

HealthKit iOS8 by
HealthKit iOS8

Intro: What it’s for?  

HealthKit is a framework that allows you to store health data to a persistent store on the users device.  We will begin with an app from Part 1 but we will take some detours that are important to understand so bare with me.

The first steps are:

– Create a tab bar application in Swift for iPhone Only

– Rename First and Second view controllers to Profile and Journal and make them UITableViewControllers

– In Capabilities turn on HealthKit

HealthKit, (HK), requires permissions to access the health store since most of this data is considered confidential.  So to do this, move over to the AppDelegate.swift.  Add this to appDidFinishLaunching method in AppDelegate:

if (HKHealthStore.isHealthDataAvailable() == true) {

self.healthStore = HKHealthStore() //needs to be var for it to work?

var writeDataTypes = self.dataTypesToWrite()

var readDataTypes = self.dataTypesToRead()

self.healthStore!.requestAuthorizationToShareTypes(writeDataTypes, readTypes: readDataTypes, completion: { (success, error) -> Void in

NSLog(“success \(error)”)

if (!success) {

NSLog(“You didn’t allow HealthKit to access these read/write data types. In your app, try to handle this error gracefully when a user decides not to provide access. The error was: %@. If you’re using a simulator, try it on a device.”, error)

//Present VC


} else {

NSLog(“success authorizing the healthstore!”)

NSLog(“writeDataTypes is%@”,writeDataTypes)

NSLog(“readDataTypes is%@”,readDataTypes)


// Handle success in your app here.




This requests permission from the user’s health store (on their device) in order to read and write personal data.  The user will be prompted to authorize whatever data he or she feels comfortable with.

Those NSSets containing the user data to read and write are created like so:

func dataTypesToWrite () -> (NSSet) {

var dietaryCalorieEnergyType: HKQuantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryEnergyConsumed)

var activeEnergyBurnType: HKQuantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned)

var heightType: HKQuantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)

var weightType: HKQuantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)

var aSet: NSSet = NSSet(objects: dietaryCalorieEnergyType, activeEnergyBurnType, heightType, weightType)

return aSet


We do something a little different in the read types:

func dataTypesToRead () -> NSSet {

let values = [HKQuantityTypeIdentifierDietaryEnergyConsumed,






return values.reduce(NSMutableSet()) { (var theSet, let identifier) in

if identifier != nil {

if let something = HKCharacteristicType.characteristicTypeForIdentifier(identifier) {


} else if let quantity = HKQuantityType.quantityTypeForIdentifier(identifier) {




return theSet



And finally, since we are going to be using the health store to read and write from many view controllers so we need to propagate our central health store throughout those view controllers.  So we need to use this method:

func setupHealthStoreForTabBarControllers () -> () {

var tabBarController = self.window!.rootViewController as UITabBarController

for navigationController: UINavigationController in tabBarController.viewControllers as Array {

var viewController = navigationController.topViewController

if viewController.isKindOfClass(ProfileViewController) {

var profileViewController: ProfileViewController = viewController as ProfileViewController

profileViewController.healthStore = self.healthStore!

} else if viewController.isKindOfClass(JournalViewController) {

var journalViewController: JournalViewController = viewController as JournalViewController

journalViewController.healthStore = self.healthStore!

} else if viewController.isKindOfClass(EnergyViewController) {

var energyViewController: EnergyViewController = viewController as EnergyViewController

energyViewController.healthStore = self.healthStore!




Now our app has access to our health store.  So recapping what we’ve done in this intro part, we basically requested permission from the health store, specified the data types to read and write and finally propagated our fully authorized health store to our child view controllers.

This is what our storyboard will look like:

Storyboard for HealtKit App
Storyboard for HealthKit App


Here we start out with a tab bar controller with 3 UITableViewControllers as children.  The best way to do this is to drag UITableViewControllers from the Object Library in case you removed the original First and Second placeholder view controllers supplied by the template.  But you could also just drag a tableview and a cell into each of those 2 supplied view controllers and drag an additional one into the storyboard, its up to you.  Then select each of the 3, one by one, and in Editor -> Embed in Navigation Controller.

Here is the ProfileViewController:

HealthKit iOS8 App by
HealthKit iOS8 App – Profile

As you can see, these are not prototype-dynamic cells but rather custom static cells.  In this case we have given the UINavBar a title and we have divided up the tableview into 3 sections: one for the users age, another for the users height and the last one for the users weight.  You can do this by setting the Sections property of the tableview in the Attributes Inspector, setting the style to Grouped and giving each section a name.

The Journal view controller is the only one that has prototype cells actually.  It looks like this:

HealthKit App iOS8 by
HealthKit App iOS8 – Journal


Here we will simply create a tableview with dynamically populated data from a hardcoded array.  The type of cell is Detail Style and we add a button on the top right.  The idea here is that the user can select items from a list that provide a certain number of calories or joules as input.  Remember, this is the Energy Consumption tab where the user can specify his daily intake.  So of course the “Add” button calls a view controller where the user can select from a list of items:

HealthKit app iOS8 by
HealthKit app iOS8 – FoodPicker


Ok so this one also has dynamic cells, this is the tableview that will actually be filled with the hardcoded items.  Once the user selects an item, it will be passed back to the Journal view controller.  This is the FoodPicker view controller.

Finally here is the EnergyViewController which will basically unify all data:

HealthKit app iOS8 by
HealthKit app iOS8

Wait!  What do you mean all the data, so far we only have the profile data read from the health store and consumed data, what about the workout?  Well that comes in the next view controller but for now, suffice it to say that this is a static table view cell with data fed in by:
Active Energy Burned = what you burn exercising

Resting Basal Burn = what you burn just breathing

Consumed Energy = what you ate

Net Energy = your final tally for the day


You input the Active Energy from the Workout view controller called when you tap the “Add” button in the Energy view controller which looks like this:

HealthKit app iOS8 by
HealthKit app iOS8


Notice something important here, we are capturing workout specific data such as laps, time, meters and pace.  This is not health data per se.  And that is precisely what HealthStore was NOT made for.  Its important to make this distinction because if you open your Health app you will not find laps, meters, km biked, tennis sets played.  That is workout-specific data and the only specific data Health app records, is Steps, because its something the iPhone can record by itself.  The Health app and the health store was conceived to record health data and it can’t very well cover all sport-specific needs.  However all that workout-specific data, laps swam, km biked or sets played, translates, somehow, into calories burned.  Now THAT is a point of convergence for all workouts and that is the kind of thing stored by the health store.  Take a look at your Health app and you will see a Health Data icon which lets you see the kinds of data the app stores.

So why is this important, well, as you will see, we will be storing energy in and energy out.  But we are still capturing laps and meters and time from the user and of course that IS important to the user.  He or she will still want to see their progress in terms of laps and time.  So we will need to incorporate CoreData in the end, in order to store that kind of data.

Ok in the next part (Part 2) we will look at the core of health data in iOS, HKObjects and how to use them!


Translate »