HealthKit for iOS8: Part 5

iOS 8 HealthKit Santiapps Marcio Valenzuela
iOS 8 HealthKit

Jumping right in, our Energy view controller class starts out like this:

import Foundation

import UIKit

import HealthKit

class EnergyViewController: UITableViewController {

var energyFormatter: NSEnergyFormatter {

var energyFormatter: NSEnergyFormatter?

var onceToken: dispatch_once_t = 0

dispatch_once(&onceToken, {

energyFormatter = NSEnergyFormatter()

energyFormatter?.unitStyle = NSFormattingUnitStyle.Long

energyFormatter?.forFoodEnergyUse = true

energyFormatter?.numberFormatter.maximumFractionDigits = 2

})

return energyFormatter!

}

// No required initWithCoder pasted in...

var  healthStore:HKHealthStore?

@IBOutlet weak var activeEnergyBurnedValueLabel: UILabel?

@IBOutlet weak var restingEnergyBurnedValueLabel: UILabel?

@IBOutlet weak var consumedEnergyValueLabel: UILabel?

@IBOutlet weak var netEnergyValueLabel: UILabel?

var activeEnergyBurned: Double = 0

var restingEnergyBurned: Double = 0

var consumedEnergy: Double = 0

var netEnergy: Double = 0

}

We take care of our imports, subclass UITableViewController, create our NSEnergyFormatter again, our health store property and then we create 4 UILabel outlets to display the values and 4 Doubles to store our energy values to be displayed.  What we are going to do here is just as important as how.  We will have 3 values which will compute a 4th one.  The 4th value is Net Energy which could be positive if we eat more or negative if we exercise more.  The other 3 are:

  • Active Energy Burned which will be populated from any workout sessions.
  • Resting Energy Burned which will be calculated automatically for us based on our profile.
  • Consumed Energy which will be input by the user in the Journal via the FoodPicker.

Ok let’s cover the view controller lifecycle methods.  viewDidLoad will be empty because instead we will use viewWillAppear:

override func viewWillAppear(animated: Bool) {

super.viewWillAppear(animated)

self.refreshControl?.addTarget(self, action:"refreshStatistics", forControlEvents:UIControlEvents.ValueChanged)

self.refreshStatistics()

NSNotificationCenter.defaultCenter().addObserver(self, selector:"refreshStatistics", name:UIApplicationDidBecomeActiveNotification, object:nil)

}

override func viewDidDisappear(animated: Bool) {

NSNotificationCenter.defaultCenter().removeObserver(self, name:UIApplicationDidBecomeActiveNotification, object:nil)

}

Here we set our refreshControl to call the refreshStatistics method.  Then we also add ourselves as observer to notifications when the application becomes active.  As always, we clean up on exit when the view disappears.

Now the method that gets called on every viewWillAppear and you’ll understand why it couldn’t be placed in the viewDidLoad:

func refreshStatistics () -> () {

self.refreshControl?.beginRefreshing()

var energyConsumedType: HKQuantityType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryEnergyConsumed)

var activeEnergyBurnType: HKQuantityType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned)

self.fetchSumOfSamplesTodayForType(energyConsumedType, unit:HKUnit.jouleUnit(), withCompletion: { (totalJoulesConsumed:Double, error:NSError?) -> () in

 

self.fetchSumOfSamplesTodayForType(activeEnergyBurnType, unit: HKUnit.jouleUnit(), withCompletion: { (activeEnergyBurned, error:NSError?) -> () in

self.fetchTotalBasalBurn({ (basalEnergyBurn, error) -> () in

if (basalEnergyBurn == nil) {

NSLog("An error occurred trying to compute the basal energy burn. In your app, handle this gracefully. Error: \(error)")

}

if (basalEnergyBurn != nil) {

// Update the UI with all of the fetched values.

dispatch_async(dispatch_get_main_queue(), {

self.activeEnergyBurned = activeEnergyBurned

self.activeEnergyBurnedValueLabel!.text = self.energyFormatter.stringFromJoules(self.activeEnergyBurned)

self.restingEnergyBurned = basalEnergyBurn!.doubleValueForUnit(HKUnit.jouleUnit())

self.restingEnergyBurnedValueLabel!.text = self.energyFormatter.stringFromJoules(self.restingEnergyBurned)

self.consumedEnergy = totalJoulesConsumed

self.consumedEnergyValueLabel!.text = self.energyFormatter.stringFromJoules(self.consumedEnergy)

self.netEnergy = self.consumedEnergy - self.activeEnergyBurned - self.restingEnergyBurned

self.netEnergyValueLabel!.text = self.energyFormatter.stringFromJoules(self.netEnergy)

self.refreshControl?.endRefreshing()

}) //END OF DISPATCH

}

}) //END OF self.fetchTotalBasalBurn

}) //END OF self.fetchSumOf2..

}) //END OF self.fetchSumOf1...

}

First we set our control to begin refreshing.  Next we create 2 type identifiers for DietaryEnergyConsumed and ActiveEnergyBurned.  Next we call 2 fetches, first for energyConsumedType and then for activeEnergyBurnType.  Then we throw in a basal burn calculation.  We will look at the basal or resting energy burn methods next but, just notice that if they return nil, we log an error, if its not nil, we set our labels to the values of the calculated energies.  Finally we end refreshing.

Ok so let’s look at the meaty methods.  First, the fetchSumOfSamplesTodayForType method:

func fetchSumOfSamplesTodayForType(quantityType:HKQuantityType, unit:HKUnit, withCompletion completion:((Double, NSError?) -> Void)? ) {

let predicate: NSPredicate = self.predicateForSamplesToday()

let query = HKStatisticsQuery(quantityType: quantityType, quantitySamplePredicate: predicate, options: .CumulativeSum) {query, result, error in

let sum = result?.sumQuantity()

if completion != nil {

let value: Double = sum?.doubleValueForUnit(unit) ?? 0.0    //NOTE: use 0.0 when sum is nil

completion!(value, error)

}

}

self.healthStore?.executeQuery(query)

}

Here we create a HKStatisticsQuery fetch which is a bit different from the regular HKQuery.  The reason is that we want to return the .CumulativeSum of all samples, not just the latest one.  We could fetch all samples for today but we would have to add them manually.  Since cumulative sums is quite common, HealthKit has a method for that.  The query returns a result and we set it to sum.  We then return that value in the completion handler.

Now the basal burn or resting energy burn is composed of 3 methods and an extension:

func fetchTotalBasalBurn( completion:(basalEnergyBurn: HKQuantity?, error: NSError?) -> ()?) {

var todayPredicate: NSPredicate = self.predicateForSamplesToday()

var weightType: HKQuantityType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)

var heightType: HKQuantityType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)

self.healthStore?.aapl_mostRecentQuantitySampleOfType(weightType, predicate:nil, completion: { (weight, error) -> () in

if weight == nil {

completion(basalEnergyBurn: nil, error:error)

return

}

self.healthStore?.aapl_mostRecentQuantitySampleOfType(heightType, predicate: todayPredicate, completion: { (height, error) -> () in

if height == nil {

completion(basalEnergyBurn: nil, error:error)

return

}

var innerError: NSError?    //NOTE: this var receives errors from dateOfBirthWithError or biologicalSexWithError

var dateOfBirth: NSDate? = self.healthStore?.dateOfBirthWithError(&innerError)

if dateOfBirth == nil {

completion(basalEnergyBurn: nil, error:innerError)

return

}

var biologicalSexObject: HKBiologicalSexObject? = self.healthStore?.biologicalSexWithError(&innerError)

if biologicalSexObject == nil {

completion(basalEnergyBurn: nil, error:error)

return

}

var basalEnergyBurn: HKQuantity = self.calculateBasalBurnTodayFromWeight(weight!, height:height!, dateOfBirth:dateOfBirth, biologicalSex:biologicalSexObject)!

completion(basalEnergyBurn: basalEnergyBurn, error: nil)

})

})

}

It may look daunting…oh who are we kidding, it is.  And it only gets worse!

First we create type identifiers for BodyMass and height.  We also create a predicate calling a separate method which we will see later.  Next we fetch the most recent quantity from the health store.  You will recall we did the exact same thing in the Profile view controller.  We are doing the same thing here but using a helper method thats included in an extension that others can use, not just this method.  So first we ask the health store for the weightType, if nil we return nil in the completion handler.  Next we ask for the weight and ditto with the completion handler.  Next we ask for dateOfBirth and biologicalSex.  This is the same we way asked for DOB in the Profile view controller.  But we have to return a completion handler on both calls, so we do.  Finally we set our basal burn HKQuantity to be saved to the health store by calling the calculateBasalBurnTodayFromWeight and we pass in our values for height, weight, sex and dob.  Once again we return a fully qualified completion handler this time.

So let’s take a look at the calculateBasalBurnTodayFromWeight method:

func calculateBasalBurnTodayFromWeight(weight:HKQuantity?, height:HKQuantity?, dateOfBirth:NSDate?, biologicalSex:HKBiologicalSexObject?) -> (HKQuantity?) {

// Only calculate Basal Metabolic Rate (BMR) if we have enough information about the user

if weight == nil || height == nil || dateOfBirth == nil || biologicalSex == nil {

return nil

}

var lenghtUnit: HKUnit = HKUnit(fromString: "cm")

var someHeight = height?.doubleValueForUnit(lenghtUnit)

let heightInCentimeters: Double = someHeight!

let weightInKilograms: Double = weight!.doubleValueForUnit(HKUnit.gramUnitWithMetricPrefix(HKMetricPrefix.Kilo))

let now: NSDate = NSDate()

let ageComponents: NSDateComponents = NSCalendar.currentCalendar().components(.CalendarUnitYear, fromDate:dateOfBirth!, toDate:now, options:nil)

let ageInYears:Int = ageComponents.year

// BMR is calculated in kilocalories per day.

let BMR: Double = self.calculateBMRFromWeight(weightInKilograms, heightInCentimeters:heightInCentimeters, ageInYears:ageInYears, biologicalSex:(biologicalSex?.biologicalSex)!)

// Figure out how much of today has completed so we know how many kilocalories the user has burned.

let startOfToday:NSDate = NSCalendar.currentCalendar().startOfDayForDate(now)

let endOfToday:NSDate = NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitDay, value:1, toDate:startOfToday, options:nil)!

let secondsInDay: NSTimeInterval = endOfToday.timeIntervalSinceDate(startOfToday)

let percentOfDayComplete: Double = now.timeIntervalSinceDate(startOfToday) / secondsInDay

let kilocaloriesBurned: Double = BMR * percentOfDayComplete

return HKQuantity(unit: HKUnit.kilocalorieUnit(), doubleValue: kilocaloriesBurned)

}

First we make sure we have all the parameters needed to calculate basal or resting energy.  Remember, this is the energy burned by your body, just by carrying out its normal functions, breathing, metabolism etc.  No exercise is included here.

Then we create a unit for the height and format our height.  Ditto for our weight!  Next we calculate our age once again.  Finally we create a BMR variable which will be set by calling yet another method.   The BMR is Basal Metabolic Rate and it is calculated as a percentage of the day that has expired so far.  So basically you burn calories no matter what you do, unless you are dead.  In the morning your body will have burned a certain % of those calories.  As the day progresses, we burn more and so on and so forth.

This means we need to calculate how many seconds (NSTimeInterval) have passed since the beginning of the day.  This gives us a % of the day completed.  We then simply multiply that ratio by the BMR that a person with that weight, height, sex and age is supposed to have in a day and we get our result.

Finally we return an HKQuantity for the kilocalories burned according to the BMR and the % of day complete.

Here is a small method to take a break:

func predicateForSamplesToday () -> (NSPredicate) {

let calendar: NSCalendar = NSCalendar.currentCalendar()

let now: NSDate = NSDate()

let startDate: NSDate = calendar.startOfDayForDate(now)

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

return HKQuery.predicateForSamplesWithStartDate(startDate, endDate:endDate, options:HKQueryOptions.StrictStartDate)

}

What we are doing here is creating a start and end date for today instead of having to re-write that code everytime.

So how do you calculate BMR:

func calculateBMRFromWeight(weightInKilograms:Double, heightInCentimeters:Double, ageInYears:Int, biologicalSex:HKBiologicalSex) -> (Double) {

var BMR:Double

if (biologicalSex == HKBiologicalSex.Male) {

BMR = 66.0 + (13.8*weightInKilograms) + (5*heightInCentimeters) - (6.8*Double(ageInyears))

} else {

BMR = 655.0 + (9.6*weightInKilograms) + (1.8*heightInCentimeters) - (4.7*Double(ageInyears))

}

return BMR

}

It’s sex dependent and basically a simple linear formula.  Big whoop.  Ok.

Now let’s look at the meaty helper extension we saw earlier:

extension HKHealthStore {

func aapl_mostRecentQuantitySampleOfType(quantityType: HKQuantityType, predicate:NSPredicate?, completion:( (HKQuantity?, NSError?) -> () )? )  {

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

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

if (results == nil) {

if (completion != nil) {

completion?(nil, error)

} //END OF IF 2...

return

} // END OF IF 1...

if ((completion) != nil) {

// If quantity isn't in the database, return nil in the completion block.

var resultados = results as NSArray

var quantitySample: HKQuantitySample = resultados.firstObject as HKQuantitySample

var quantity: HKQuantity = quantitySample.quantity

completion?(quantity, error)

} //END OF IF

} // HKSAMPLEQUERY

self.executeQuery(query)

} // END OF FUNCTION

} //END OF EXTENSION

We create a sort descriptor as we did in the Profile, because we want to order our results by the latest.  Then we create our simple HKQuery with whatever quantityType was passed in, the predicate, limit and sortDescriptor as well as the completion handler.  If results are nil, we set our completion handler value to nil and return.  Otherwise, we set our completion handler to whatever the most recent quantity fetched is because once again we take the firstObject from that results array.

Ok the only thing left here is to prepareForSegue:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

var workoutViewController: WorkoutViewController = segue.destinationViewController as WorkoutViewController//viewController as WorkoutViewController

workoutViewController.healthStore = self.healthStore!

}

The reason we segue is that we need to take the user to the point where he can enter the only value missing.  We already calculated the resting energy value internally based on the user’s profile data.  Then we calculated the consumed energy based on what the user picked as his or her consumed foods.  So now we need to know how much energy he burnt in his workout.

Race you there (Part 6)!