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
@@ -33,6 +33,7 @@ struct ExerciseAddEditView: View {
@State private var sets: Int
@State private var weightReminderWeeks: Int
@State private var weightLastUpdated: Date?
@AppStorage("weightUnit") private var weightUnit: WeightUnit = .lb
init(exercise: Exercise, split: Split) {
self.exercise = exercise
@@ -129,7 +130,7 @@ struct ExerciseAddEditView: View {
.frame(height: 100)
.pickerStyle(.wheel)
Text("lbs")
Text(weightUnit.abbreviation)
}
}
}
@@ -28,6 +28,7 @@ struct ExerciseListView: View {
private var workouts: [Workout]
@State private var showingActivePrompt = false
@AppStorage("weightUnit") private var weightUnit: WeightUnit = .lb
private var activeWorkouts: [Workout] {
workouts.filter { $0.status == .inProgress || $0.status == .notStarted }
@@ -41,7 +42,7 @@ struct ExerciseListView: View {
ForEach(sortedExercises) { item in
ListItem(
title: item.name,
subtitle: "\(item.sets) × \(item.reps) × \(item.weight) lbs"
subtitle: "\(item.sets) × \(item.reps) × \(weightUnit.format(item.weight))"
)
.swipeActions {
Button {
@@ -18,6 +18,7 @@ struct SettingsView: View {
@AppStorage("restSeconds") private var restSeconds: Int = 45
@AppStorage("doneCountdownSeconds") private var doneCountdownSeconds: Int = 5
@AppStorage("weightUnit") private var weightUnit: WeightUnit = .lb
@State private var showingAddSplitSheet = false
var body: some View {
@@ -40,6 +41,12 @@ struct SettingsView: View {
Text("\(doneCountdownSeconds)s").foregroundColor(.secondary)
}
}
Picker("Weight Unit", selection: $weightUnit) {
ForEach(WeightUnit.allCases, id: \.self) { unit in
Text(unit.displayName).tag(unit)
}
}
} header: {
Text("Workout")
} footer: {
@@ -142,6 +149,7 @@ struct SettingsView: View {
}
.onChange(of: restSeconds) { _, _ in services.watchBridge.pushAll() }
.onChange(of: doneCountdownSeconds) { _, _ in services.watchBridge.pushAll() }
.onChange(of: weightUnit) { _, _ in services.watchBridge.pushAll() }
}
}
}
+17 -1
View File
@@ -21,6 +21,7 @@ struct SplitAddEditView: View {
@State private var name: String = ""
@State private var color: String = "indigo"
@State private var systemImage: String = "dumbbell.fill"
@State private var activityType: WorkoutActivityType = .traditionalStrength
@State private var showingIconPicker: Bool = false
@State private var showingDeleteConfirmation: Bool = false
@@ -33,6 +34,7 @@ struct SplitAddEditView: View {
_name = State(initialValue: split.name)
_color = State(initialValue: split.color)
_systemImage = State(initialValue: split.systemImage)
_activityType = State(initialValue: split.activityTypeEnum)
}
}
@@ -71,6 +73,18 @@ struct SplitAddEditView: View {
}
}
Section {
Picker("Activity Type", selection: $activityType) {
ForEach(WorkoutActivityType.allCases, id: \.self) { type in
Label(type.displayName, systemImage: type.systemImage).tag(type)
}
}
} header: {
Text("Activity Type")
} footer: {
Text("Determines how this workout is categorized in Apple Health and how it credits your Activity rings.")
}
if let split = split {
Section(header: Text("Exercises")) {
NavigationLink {
@@ -136,6 +150,7 @@ struct SplitAddEditView: View {
doc.name = name
doc.color = color
doc.systemImage = systemImage
doc.activityType = activityType.rawValue
doc.updatedAt = Date()
Task { await sync.save(split: doc) }
} else {
@@ -150,7 +165,8 @@ struct SplitAddEditView: View {
order: existing.count,
createdAt: Date(),
updatedAt: Date(),
exercises: []
exercises: [],
activityType: activityType.rawValue
)
Task { await sync.save(split: doc) }
}
+2 -1
View File
@@ -21,6 +21,7 @@ struct SplitDetailView: View {
@State private var showingSplitEditSheet: Bool = false
@State private var itemToEdit: Exercise? = nil
@State private var itemToDelete: Exercise? = nil
@AppStorage("weightUnit") private var weightUnit: WeightUnit = .lb
var body: some View {
Form {
@@ -36,7 +37,7 @@ struct SplitDetailView: View {
ForEach(sortedExercises) { item in
ListItem(
title: item.name,
subtitle: "\(item.sets) × \(item.reps) × \(item.weight) lbs"
subtitle: "\(item.sets) × \(item.reps) × \(weightUnit.format(item.weight))"
)
.swipeActions {
Button {
@@ -244,6 +244,7 @@ struct ExerciseView: View {
struct PlanTilesView: View {
let log: WorkoutLogDocument
@AppStorage("weightUnit") private var weightUnit: WeightUnit = .lb
var body: some View {
if LoadType(rawValue: log.loadType) == .duration {
@@ -257,7 +258,7 @@ struct PlanTilesView: View {
HStack(spacing: 0) {
PlanTile(label: "Sets", value: "\(log.sets)")
PlanTile(label: "Reps", value: "\(log.reps)")
PlanTile(label: "Weight", value: "\(log.weight) lbs")
PlanTile(label: "Weight", value: weightUnit.format(log.weight))
}
}
}
@@ -22,6 +22,7 @@ struct PlanEditView: View {
@State private var durationMinutes: Int = 0
@State private var durationSeconds: Int = 0
@State private var selectedLoadType: LoadType = .weight
@AppStorage("weightUnit") private var weightUnit: WeightUnit = .lb
var body: some View {
NavigationStack {
@@ -77,7 +78,7 @@ struct PlanEditView: View {
.foregroundColor(.secondary)
Picker("Weight", selection: $weight) {
ForEach(0...300, id: \.self) { num in
Text("\(num) lbs").tag(num)
Text(weightUnit.format(num)).tag(num)
}
}
.pickerStyle(.wheel)
@@ -27,6 +27,8 @@ struct WeightProgressionChartView: View {
)
}
@AppStorage("weightUnit") private var weightUnit: WeightUnit = .lb
private var weightData: [WeightDataPoint] {
logs.map { WeightDataPoint(date: $0.date, weight: $0.weight) }
}
@@ -97,11 +99,11 @@ struct WeightProgressionChartView: View {
? Int((Double(weightDifference) / Double(firstWeight)) * 100)
: 0
if percentIncrease >= 20 {
return "Amazing progress! You've increased your weight by \(weightDifference) lbs (\(percentIncrease)%)!"
return "Amazing progress! You've increased your weight by \(weightUnit.format(weightDifference)) (\(percentIncrease)%)!"
} else if percentIncrease >= 10 {
return "Great job! You've increased your weight by \(weightDifference) lbs (\(percentIncrease)%)!"
return "Great job! You've increased your weight by \(weightUnit.format(weightDifference)) (\(percentIncrease)%)!"
} else {
return "You're making progress! Weight increased by \(weightDifference) lbs. Keep it up!"
return "You're making progress! Weight increased by \(weightUnit.format(weightDifference)). Keep it up!"
}
} else if weightDifference == 0 {
return "You're maintaining consistent weight. Focus on form and consider increasing when ready!"
@@ -30,6 +30,8 @@ struct WorkoutLogListView: View {
@State private var logToDelete: WorkoutLogDocument?
@State private var addedLog: LogRoute?
@State private var logToEdit: LogRoute?
@State private var summaryRoute: LogRoute?
@AppStorage("weightUnit") private var weightUnit: WeightUnit = .lb
/// Drives a programmatic push keyed by a log id, used for the freshly-added
/// exercise ( progress flow) and the Edit swipe ( detail/edit screen). Rows
@@ -70,6 +72,12 @@ struct WorkoutLogListView: View {
}
} else {
Form {
if doc.status == WorkoutStatus.completed.rawValue, doc.metrics != nil {
Section("Summary") {
WorkoutMetricsView(workout: workout)
}
}
Section(header: Text(label)) {
ForEach(sortedLogs) { log in
NavigationLink {
@@ -184,6 +192,12 @@ struct WorkoutLogListView: View {
} message: {
Text(endProgressMessage)
}
.sheet(item: $summaryRoute) { route in
WorkoutSummaryView(workoutID: route.id) {
summaryRoute = nil
dismiss()
}
}
}
/// The paged run flow, fully wired into the live channel: it broadcasts this device's
@@ -314,7 +328,9 @@ struct WorkoutLogListView: View {
doc.endKeepingProgress()
let snapshot = doc
Task { await sync.save(workout: snapshot) }
dismiss()
// Show the summary (metrics fill in live as they arrive) instead of leaving
// immediately; dismissing the summary returns to the log list.
summaryRoute = LogRoute(id: snapshot.id)
}
/// Throw the workout away entirely (soft-delete via the tombstone path).
@@ -336,7 +352,7 @@ struct WorkoutLogListView: View {
return "\(log.sets) × \(secs) sec"
}
} else {
return "\(log.sets) × \(log.reps) reps × \(log.weight) lbs"
return "\(log.sets) × \(log.reps) reps × \(weightUnit.format(log.weight))"
}
}
}
@@ -349,6 +365,7 @@ struct SplitExercisePickerSheet: View {
let split: Split?
let existingExerciseNames: Set<String>
let onExerciseSelected: (Exercise) -> Void
@AppStorage("weightUnit") private var weightUnit: WeightUnit = .lb
private var availableExercises: [Exercise] {
guard let split else { return [] }
@@ -369,7 +386,7 @@ struct SplitExercisePickerSheet: View {
VStack(alignment: .leading) {
Text(exercise.name)
.foregroundColor(.primary)
Text("\(exercise.sets) × \(exercise.reps) × \(exercise.weight) lbs")
Text("\(exercise.sets) × \(exercise.reps) × \(weightUnit.format(exercise.weight))")
.font(.caption)
.foregroundColor(.secondary)
}
@@ -237,8 +237,9 @@ struct SplitPickerSheet: View {
)
Task { await sync.save(workout: doc) }
// Bring the Apple Watch up into the session so the user can run it from the wrist.
services.workoutLauncher.launchWatchWorkout()
// Bring the Apple Watch up into the session so the user can run it from the wrist,
// tagged with the split's activity type so the saved Health workout is categorized.
services.workoutLauncher.launchWatchWorkout(activityType: split.activityTypeEnum.hkActivityType)
dismiss()
}
}
@@ -0,0 +1,180 @@
//
// WorkoutSummaryView.swift
// Workouts
//
// Copyright 2025 Rouslan Zenetl. All Rights Reserved.
//
import SwiftUI
import SwiftData
/// Post-workout summary shown right after a workout finishes. Queried by id so the
/// health metrics (calories, heart rate) fill in live as they arrive from the
/// watch over the bridge, or from the phone's estimate a few seconds after ending.
struct WorkoutSummaryView: View {
@Environment(\.dismiss) private var dismiss
@Query private var workouts: [Workout]
let onDone: () -> Void
init(workoutID: String, onDone: @escaping () -> Void) {
self.onDone = onDone
_workouts = Query(filter: #Predicate<Workout> { $0.id == workoutID })
}
private var workout: Workout? { workouts.first }
var body: some View {
NavigationStack {
Group {
if let workout {
ScrollView {
VStack(spacing: 20) {
Image(systemName: "checkmark.seal.fill")
.font(.system(size: 48))
.foregroundStyle(.green)
.padding(.top, 8)
Text(workout.splitName ?? Split.unnamed)
.font(.title2.bold())
WorkoutMetricsView(workout: workout)
if workout.metrics == nil {
Label("Saving to Apple Health…", systemImage: "heart.text.square")
.font(.footnote)
.foregroundStyle(.secondary)
}
}
.padding()
}
} else {
// The workout was removed (e.g. discarded) nothing to summarize.
ContentUnavailableView("Workout Ended", systemImage: "checkmark.circle")
}
}
.navigationTitle("Summary")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .confirmationAction) {
Button("Done") { onDone() }
}
}
}
}
}
// MARK: - Metric tiles (shared by the summary sheet and the per-workout detail)
/// Renders the available health/strength metrics for a finished workout as a tile
/// grid plus an optional heart-rate-zone bar. Reused by `WorkoutSummaryView` and the
/// completed-workout detail section.
struct WorkoutMetricsView: View {
let workout: Workout
@AppStorage("weightUnit") private var weightUnit: WeightUnit = .lb
private var metrics: WorkoutMetrics? { workout.metrics }
private var durationSeconds: Int? {
guard let end = workout.end else { return nil }
return max(0, Int(end.timeIntervalSince(workout.start)))
}
private var volume: Double {
metrics?.totalVolume ?? WorkoutVolume.total(WorkoutDocument(from: workout).logs)
}
var body: some View {
VStack(spacing: 16) {
LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: 12) {
if let durationSeconds {
MetricTile(icon: "clock.fill", tint: .blue, value: durationText(durationSeconds), label: "Duration")
}
if let kcal = metrics?.activeEnergyKcal {
MetricTile(icon: "flame.fill", tint: .orange, value: "\(Int(kcal.rounded()))", label: "Active cal")
}
if let avg = metrics?.avgHeartRate {
MetricTile(icon: "heart.fill", tint: .red, value: "\(Int(avg.rounded()))", label: "Avg BPM")
}
if let max = metrics?.maxHeartRate {
MetricTile(icon: "bolt.heart.fill", tint: .pink, value: "\(Int(max.rounded()))", label: "Max BPM")
}
if volume > 0 {
MetricTile(icon: "scalemass.fill", tint: .purple, value: volumeText, label: "Volume")
}
}
if let zones = metrics?.hrZoneSeconds, zones.contains(where: { $0 > 0 }) {
HRZoneBar(zoneSeconds: zones)
}
if metrics?.source == .phoneEstimate {
Text("Calories estimated — wear your Apple Watch for measured stats.")
.font(.caption2)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
}
}
}
private var volumeText: String {
"\(Int(volume.rounded())) \(weightUnit.abbreviation)"
}
private func durationText(_ seconds: Int) -> String {
let minutes = seconds / 60
if minutes >= 60 { return "\(minutes / 60)h \(minutes % 60)m" }
return "\(minutes)m \(seconds % 60)s"
}
}
struct MetricTile: View {
let icon: String
let tint: Color
let value: String
let label: String
var body: some View {
VStack(spacing: 4) {
Image(systemName: icon)
.font(.title2)
.foregroundStyle(tint)
Text(value)
.font(.title3.bold())
.monospacedDigit()
Text(label)
.font(.caption2)
.foregroundStyle(.secondary)
}
.frame(maxWidth: .infinity)
.padding(.vertical, 10)
.background(.quaternary.opacity(0.4), in: RoundedRectangle(cornerRadius: 12))
}
}
/// Proportional stacked bar of time spent in each of the 5 heart-rate zones (lowhigh).
struct HRZoneBar: View {
let zoneSeconds: [Double]
private let colors: [Color] = [.blue, .green, .yellow, .orange, .red]
var body: some View {
let total = max(zoneSeconds.reduce(0, +), 1)
VStack(alignment: .leading, spacing: 6) {
Text("Heart Rate Zones")
.font(.caption)
.foregroundStyle(.secondary)
GeometryReader { geo in
HStack(spacing: 2) {
ForEach(0..<5, id: \.self) { zone in
if zoneSeconds[zone] > 0 {
colors[zone]
.frame(width: max(2, geo.size.width * (zoneSeconds[zone] / total)))
}
}
}
}
.frame(height: 12)
.clipShape(Capsule())
}
.frame(maxWidth: .infinity, alignment: .leading)
}
}