Group Group Group Group Group Group Group Group Group

Distance and Pace from HealthKit

I’m modifying the “Groundhog” app. I need to display total distance and current pace.

I’ve modified the storyboards appropriately to add two labels for those measurements. The distance label works well and exactly as expected however I get wildly inaccurate results for pace. I using the

workoutSessionService(service: WorkoutSessionService, didUpdateDistance distance:Double)

method to update both. I created two class variable 1)lastDistance and 2)lastDate to help in the pace calculation. Below is my modified code for the method above. I’m assuming that the elapsedTime calculation gives me seconds and that distance is the cumulative distance traveled. Am I missing something obvious?

func workoutSessionService(service: WorkoutSessionService, didUpdateDistance distance:Double) {

//get distance traveled for this interval
let thisDistance = (distance - lastDistance)
print("Distance: \(thisDistance)")

//get time since last update
let elapsedTime = NSDate().timeIntervalSinceDate(lastDate)
print("Elapsed time: \(elapsedTime)")

//calclulate pace in minutes per mile(or kilometer based on locale)
let thisPace = elapsedTime/thisDistance// * 60
print("Pace: \(thisPace)")

//update prevvious values
lastDate = NSDate()
lastDistance = distance


//set up formatter for pace
let formatter = NSDateComponentsFormatter()
formatter.allowedUnits = [.Minute, .Second ]
formatter.zeroFormattingBehavior = .Pad

//update pace label
let paceString = formatter.stringFromTimeInterval(thisPace)
print("pace    : \(paceString)")
paceLabel.setText(paceString)

//update total distance label
totalDistanceLabel.setText(distanceFormatter.stringFromValue(distance, unit: distanceFormatterUnit))

}