A builder object that incrementally constructs a workout.


class HKWorkoutBuilder : NSObject


Incrementally collect samples and events associated with a workout. When the workout ends, call finishWorkout(completion:) to create an HKWorkout sample and save it to the HealthKit store.

For watchOS, use an HKWorkoutSession and an HKLiveWorkoutBuilder instead.


Creating the Builder

init(healthStore: HKHealthStore, configuration: HKWorkoutConfiguration, device: HKDevice?)

Returns a new workout builder object that is not connected to a workout session or other data source.

var device: HKDevice?

The device associated with the workout.

var workoutConfiguration: HKWorkoutConfiguration

The configuration information for the workout.

Starting the Workout

func beginCollection(withStart: Date, completion: (Bool, Error?) -> Void)

Sets the workout’s start date and begins building the workout.

var startDate: Date?

The workout’s start date and time.

func elapsedTime(at: Date) -> TimeInterval

Calculates the duration of the workout at the specified time.

Associating Samples with the Workout

func add([HKSample], completion: (Bool, Error?) -> Void)

Adds a sample to be associated with the workout.

func seriesBuilder(for: HKSeriesType) -> HKSeriesBuilder?

Returns the series builder for the specified type, creating a new builder, if necessary.

func statistics(for: HKQuantityType) -> HKStatistics?

Returns the statistics calculated for matching samples added to the workout.

Adding Metadata to the Workout

var metadata: [String : Any]

The metadata the builder saves with the workout.

Adding Events to the Workout

var workoutEvents: [HKWorkoutEvent]

The list of events added to the workout.

Ending the Workout

func endCollection(withEnd: Date, completion: (Bool, Error?) -> Void)

Stops the collection of data, sets the workout’s end date, and deactivates the workout builder.

var endDate: Date?

The workout’s end date and time.

func finishWorkout(completion: (HKWorkout?, Error?) -> Void)

Creates the workout, using the samples and events added to the builder, and saves it to the HealthKit store.

func discardWorkout()

Stops the collection of data and discards the current results without saving the workout.


Inherits From

Conforms To

See Also


Adding Samples to a Workout

Create associated samples that add details to a workout.

class HKWorkout

A workout sample that stores information about a single physical activity.

class HKWorkoutType

A type that identifies samples that store information about a workout.

let HKWorkoutTypeIdentifier: String

The workout type identifier.

enum HKWorkoutActivityType

The type of activity performed during a workout.

class HKWorkoutEvent

An object representing an important event during a workout.