Save workouts to Apple Health with live watch metrics and a post-workout summary

Watch sessions now run an HKLiveWorkoutBuilder: heart rate and active
energy are collected live (shown in an in-workout HUD), saved to Health
as a real HKWorkout on completion, and carried back to the phone as
WorkoutMetrics on the workout document. Phone-only workouts get an
estimated Health workout (MET x bodyweight x duration) after a 10s
debounce that a late-arriving watch session cancels; a launch sweep
backfills workouts completed within the last day. Dedupe is keyed on
metrics.healthKitWorkoutUUID plus the metrics source.

Splits gain an activity type (strength, functional, HIIT, core, cardio,
cycling) that categorizes the Health workout and picks the MET value.
A post-workout summary sheet (duration, calories, avg/max HR, HR zones,
total volume) fills in live and is also shown on completed workouts.
Weights can now display in lb or kg (display-only relabel), synced to
the watch over the existing application context.

WorkoutDocument schema 1->2 (metrics are irreplaceable, so older apps
must quarantine rather than strip them); cache schema 2 rebuilds the
SwiftData store with the new metric columns. Deleting a workout in the
app intentionally leaves its Health record in place.
This commit is contained in:
2026-07-05 07:46:35 -04:00
parent c96b1a288b
commit 0ad93a09da
33 changed files with 950 additions and 57 deletions
+32 -1
View File
@@ -23,6 +23,11 @@ struct SplitDocument: Codable, Sendable, Equatable, Identifiable {
var createdAt: Date
var updatedAt: Date
var exercises: [ExerciseDocument]
/// Raw `WorkoutActivityType`; nil traditional strength training. Optional and
/// deliberately NOT schema-bumped: it's a minor categorization preference, so an
/// older app dropping it on rewrite (reverting to the default) is preferable to
/// quarantining the user's whole routine.
var activityType: Int?
static let currentSchema = 1
@@ -55,8 +60,16 @@ struct WorkoutDocument: Codable, Sendable, Equatable, Identifiable {
var createdAt: Date
var updatedAt: Date
var logs: [WorkoutLogDocument]
/// Health metrics captured for a finished workout (watch sensors) or estimated
/// by the phone. Nil until the workout completes and a writer fills it in. The
/// presence of `metrics.healthKitWorkoutUUID` is the dedupe signal that keeps the
/// watch and the phone from both writing the same workout to Health.
var metrics: WorkoutMetrics?
static let currentSchema = 1
// Bumped 12 when `metrics` was added: the captured HR/calorie data is
// irreplaceable, so the forward-gate must quarantine these files on older apps
// rather than let them strip `metrics` on rewrite.
static let currentSchema = 2
var relativePath: String { Self.relativePath(id: id, start: start) }
@@ -125,6 +138,24 @@ struct WorkoutLogDocument: Codable, Sendable, Equatable, Identifiable {
var date: Date
}
// MARK: - Workout health metrics
/// Health metrics for one finished workout. Embedded in `WorkoutDocument` so they
/// ride the existing iCloud + Watch-bridge paths with the rest of the workout.
/// Every field except `source`/`recordedAt` is optional a phone estimate carries
/// only calories + volume, while a watch session fills in heart rate too.
struct WorkoutMetrics: Codable, Sendable, Equatable {
var activeEnergyKcal: Double?
var avgHeartRate: Double? // bpm
var maxHeartRate: Double? // bpm
var minHeartRate: Double? // bpm
var totalVolume: Double? // Σ sets×reps×weight across weighted logs
var hrZoneSeconds: [Double]? // seconds spent in each of 5 HR zones (lowhigh)
var healthKitWorkoutUUID: String?
var source: MetricSource
var recordedAt: Date
}
// MARK: - Forward-compatibility gate
/// A file whose `schemaVersion` exceeds the reader's `currentSchema` was written
+51
View File
@@ -22,6 +22,7 @@ final class Split {
var createdAt: Date = Date()
var updatedAt: Date = Date()
var jsonRelativePath: String = ""
var activityTypeRaw: Int = 0
@Relationship(deleteRule: .cascade, inverse: \Exercise.split)
var exercises: [Exercise] = []
@@ -41,6 +42,11 @@ final class Split {
static let unnamed = "Unnamed Split"
var exercisesArray: [Exercise] { exercises.sorted { $0.order < $1.order } }
var activityTypeEnum: WorkoutActivityType {
get { WorkoutActivityType(rawValue: activityTypeRaw) ?? .traditionalStrength }
set { activityTypeRaw = newValue.rawValue }
}
}
// MARK: - Exercise
@@ -107,6 +113,19 @@ final class Workout {
var updatedAt: Date = Date()
var jsonRelativePath: String = ""
// Health metrics flat columns mirroring `WorkoutMetrics` (SwiftData @Model
// can't store the nested Codable cleanly). Assemble via the `metrics` computed
// property. All nil until a workout finishes and a writer fills them in.
var metricActiveEnergyKcal: Double?
var metricAvgHeartRate: Double?
var metricMaxHeartRate: Double?
var metricMinHeartRate: Double?
var metricTotalVolume: Double?
var metricHRZoneSeconds: [Double]?
var metricHealthKitWorkoutUUID: String?
var metricSourceRaw: String?
var metricRecordedAt: Date?
@Relationship(deleteRule: .cascade, inverse: \WorkoutLog.workout)
var logs: [WorkoutLog] = []
@@ -143,6 +162,38 @@ final class Workout {
return start.formattedDate()
}
}
/// Assembles the flat `metric*` columns into a `WorkoutMetrics`, or nil when none
/// have been recorded. `source`/`recordedAt` are always set together when metrics
/// exist, so they gate presence.
var metrics: WorkoutMetrics? {
get {
guard let sourceRaw = metricSourceRaw,
let source = MetricSource(rawValue: sourceRaw),
let recordedAt = metricRecordedAt else { return nil }
return WorkoutMetrics(
activeEnergyKcal: metricActiveEnergyKcal,
avgHeartRate: metricAvgHeartRate,
maxHeartRate: metricMaxHeartRate,
minHeartRate: metricMinHeartRate,
totalVolume: metricTotalVolume,
hrZoneSeconds: metricHRZoneSeconds,
healthKitWorkoutUUID: metricHealthKitWorkoutUUID,
source: source,
recordedAt: recordedAt)
}
set {
metricActiveEnergyKcal = newValue?.activeEnergyKcal
metricAvgHeartRate = newValue?.avgHeartRate
metricMaxHeartRate = newValue?.maxHeartRate
metricMinHeartRate = newValue?.minHeartRate
metricTotalVolume = newValue?.totalVolume
metricHRZoneSeconds = newValue?.hrZoneSeconds
metricHealthKitWorkoutUUID = newValue?.healthKitWorkoutUUID
metricSourceRaw = newValue?.source.rawValue
metricRecordedAt = newValue?.recordedAt
}
}
}
// MARK: - WorkoutLog
+81
View File
@@ -34,3 +34,84 @@ enum LoadType: Int, CaseIterable, Codable, Sendable {
}
}
}
/// The kind of training a split represents used to tag the Apple Health workout
/// so it lands in the right category (and credits the rings correctly), and to pick
/// a MET value when the phone has to estimate calories without watch sensor data.
/// Persisted as its raw `Int` on `SplitDocument`; the `HKWorkoutActivityType`
/// mapping lives in `Shared/HealthKit/HealthKitMapping.swift` to keep this enum
/// HealthKit-free.
enum WorkoutActivityType: Int, CaseIterable, Codable, Sendable {
case traditionalStrength = 0 // default
case functionalStrength = 1
case hiit = 2
case coreTraining = 3
case cardio = 4
case cycling = 5
var displayName: String {
switch self {
case .traditionalStrength: "Strength Training"
case .functionalStrength: "Functional Strength"
case .hiit: "HIIT"
case .coreTraining: "Core Training"
case .cardio: "Cardio"
case .cycling: "Cycling"
}
}
var systemImage: String {
switch self {
case .traditionalStrength: "dumbbell.fill"
case .functionalStrength: "figure.strengthtraining.functional"
case .hiit: "figure.highintensity.intervaltraining"
case .coreTraining: "figure.core.training"
case .cardio: "figure.run"
case .cycling: "figure.outdoor.cycle"
}
}
/// Metabolic-equivalent value used only for the phone-side calorie estimate
/// (`kcal MET × bodyweightKg × hours`) when no watch metrics are available.
var met: Double {
switch self {
case .traditionalStrength: 5.0
case .functionalStrength: 4.0
case .hiit: 8.0
case .coreTraining: 4.0
case .cardio: 7.0
case .cycling: 7.5
}
}
}
/// Where a workout's health metrics came from: real watch sensors, or a phone-side
/// estimate written when no watch session ran. Persisted in `WorkoutMetrics`.
enum MetricSource: String, Codable, Sendable {
case watch
case phoneEstimate
}
/// Display unit for weights. The stored weight values are plain integers and are
/// never rewritten when this changes switching only relabels what's shown.
enum WeightUnit: String, CaseIterable, Codable, Sendable {
case lb
case kg
var displayName: String {
switch self {
case .lb: "Pounds (lb)"
case .kg: "Kilograms (kg)"
}
}
var abbreviation: String {
switch self {
case .lb: "lb"
case .kg: "kg"
}
}
/// Render a stored weight value with the current unit's label, e.g. "135 lb".
func format(_ value: Int) -> String { "\(value) \(abbreviation)" }
}
+6 -2
View File
@@ -27,7 +27,8 @@ extension SplitDocument {
self.init(schemaVersion: Self.currentSchema, id: split.id, name: split.name,
color: split.color, systemImage: split.systemImage, order: split.order,
createdAt: split.createdAt, updatedAt: split.updatedAt,
exercises: split.exercisesArray.map(ExerciseDocument.init(from:)))
exercises: split.exercisesArray.map(ExerciseDocument.init(from:)),
activityType: split.activityTypeRaw)
}
}
@@ -45,7 +46,8 @@ extension WorkoutDocument {
self.init(schemaVersion: Self.currentSchema, id: workout.id, splitID: workout.splitID,
splitName: workout.splitName, start: workout.start, end: workout.end,
status: workout.statusRaw, createdAt: workout.createdAt, updatedAt: workout.updatedAt,
logs: workout.logsArray.map(WorkoutLogDocument.init(from:)))
logs: workout.logsArray.map(WorkoutLogDocument.init(from:)),
metrics: workout.metrics)
}
}
@@ -83,6 +85,7 @@ enum CacheMapper {
split.createdAt = doc.createdAt
split.updatedAt = doc.updatedAt
split.jsonRelativePath = relativePath
split.activityTypeRaw = doc.activityType ?? 0
let existing = Dictionary(split.exercises.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })
var keep = Set<String>()
@@ -141,6 +144,7 @@ enum CacheMapper {
workout.createdAt = doc.createdAt
workout.updatedAt = doc.updatedAt
workout.jsonRelativePath = relativePath
workout.metrics = doc.metrics
let existing = Dictionary(workout.logs.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })
var keep = Set<String>()