Search code examples
swiftwatchkithealthkit

HKWorkoutSessionManager protocol methods not getting called


I have conformed to my WorkoutSessionManagerDelegate and have attempted to update the UI using those protocol methods but nothing in the update function is getting printed or displayed.

My setup requires initialization using context and I need to add code to update the WorkoutSessionManager when the context eventually changes.

How should I update the WorkoutSessionManager when the context eventually changes?

DashboardController.swift

class DashboardController: WKInterfaceController, WorkoutSessionManagerDelegate {

// IBOutlets

override func awakeWithContext(context: AnyObject?) {
    super.awakeWithContext(context)

    addMenuItemWithItemIcon(.Accept, title: "Save", action: #selector(DashboardController.saveSession))

    if context is WorkoutSessionContext {

   WorkoutSessionManager.sharedManager(context as! WorkoutSessionContext)

    } else {
        print("Context is not WorkoutSessionContext")
    }
}

func saveSession() {
    WorkoutSessionManager.sharedManager!.stopWorkoutAndSave()
}

func workoutSessionManager(workoutSessionManager: WorkoutSessionManager, didUpdateActiveEnergyQuantity activeEnergyQuantity: HKQuantity) {

    // nothing in this function is getting printed or displayed
    caloriesLabel.setText("\((activeEnergyQuantity.doubleValueForUnit(workoutSessionManager.energyUnit)))")
    print("\(WorkoutSessionManager.sharedManager?.energyUnit)")
    print("testing print line")

}

WorkoutsController.swift

@IBAction func startWalkingButton() {
    print("Walking start button pressed")
    presentControllerWithName("Dashboard", context: sessionContext)
    WorkoutSessionManager.sharedManager!.startWorkout(.WalkingButton)   
// no code-completion
}

Solution

  • You never called that function and to be able to call that function you must have a reference to DashboardController for you to use in your func startWalkingButton(). Since this is Watch Kit as we discussed above I do not know the best way to do this but Apples Sample Code here: https://developer.apple.com/library/ios/samplecode/WKInterfaceCatalog/Introduction/Intro.html will direct you on how to do that properly. If you need help with doing this ask the now more specific question you have.