The next code is to start or stop a workout session.
let healthStore = HKHealthStore() healthStore.startWorkoutSession(workoutSession) { (result: Bool, error: NSError?) -> Void in } healthStore.stopWorkoutSession(workoutSession) { (result: Bool, error: NSError?) -> Void in }
There is an HKWorkoutSessionDelegate that notifies session state.
protocol HKWorkoutSessionDelegate : NSObjectProtocol { func workoutSession(workoutSession: HKWorkoutSession, didChangeToState toState: HKWorkoutSessionState, fromState: HKWorkoutSessionState, date: NSDate) func workoutSession(workoutSession: HKWorkoutSession, didFailWithError error: NSError) }
[Edited] 2015/08/31
ObjC Version
HKWorkoutSession *workoutSession = [[HKWorkoutSession alloc] initWithActivityType:HKWorkoutActivityTypeRunning locationType:HKWorkoutSessionLocationTypeOutdoor]; workoutSession.delegate = self; HKHealthStore *healthStore = [HKHealthStore new]; [healthStore startWorkoutSession:workoutSession]; [healthStore stopWorkoutSession:workoutSession];
HKWrokoutSessionDelegate
- (void)workoutSession:(HKWorkoutSession *)workoutSession didChangeToState:(HKWorkoutSessionState)toState fromState:(HKWorkoutSessionState)fromState date:(NSDate *)date; - (void)workoutSession:(HKWorkoutSession *)workoutSession didFailWithError:(NSError *)error;
Note: there is a change in the method name with the latest version, see OS 2 beta 5.
stopWorkoutSession has changed to endWorkoutSession.
source share