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
+9
View File
@@ -12,6 +12,7 @@ final class AppServices {
let syncEngine: SyncEngine
let watchBridge: PhoneConnectivityBridge
let workoutLauncher = WorkoutLauncher()
let workoutHealthWriter: WorkoutHealthWriter
/// Ephemeral live-run state fed by the watch, observed by the mirror UI. Not persisted.
let liveRunState: LiveRunState
@@ -25,6 +26,10 @@ final class AppServices {
let liveRunState = LiveRunState()
self.liveRunState = liveRunState
self.watchBridge = PhoneConnectivityBridge(container: container, syncEngine: syncEngine, liveRunState: liveRunState)
let writer = WorkoutHealthWriter(container: container, syncEngine: syncEngine)
self.workoutHealthWriter = writer
syncEngine.onWorkoutCompleted = { [weak writer] doc in writer?.workoutCompleted(doc) }
syncEngine.onWatchMetricsArrived = { [weak writer] id in writer?.watchMetricsArrived(workoutID: id) }
#if DEBUG
if ScreenshotSeed.isActive { ScreenshotSeed.populate(container.mainContext) }
#endif
@@ -38,6 +43,10 @@ final class AppServices {
guard let self else { return }
await self.syncEngine.connect()
self.watchBridge.activate()
// Past the iCloud gate and cache is reconciled: request Health access and
// back-fill any recently-completed workout that never reached Health.
self.workoutHealthWriter.authorizeIfNeeded()
self.workoutHealthWriter.sweepRecentlyCompleted()
}
bootstrapTask = task
await task.value
@@ -87,11 +87,13 @@ final class PhoneConnectivityBridge: NSObject {
let restSeconds = UserDefaults.standard.object(forKey: WCPayload.restSecondsKey) as? Int ?? 45
let doneCountdownSeconds = UserDefaults.standard.object(forKey: WCPayload.doneCountdownSecondsKey) as? Int ?? 5
let weightUnit = UserDefaults.standard.string(forKey: WCPayload.weightUnitKey) ?? WeightUnit.lb.rawValue
let payload = WCPayload.encodeState(
splits: splits.map(SplitDocument.init(from:)),
workouts: workouts.map(WorkoutDocument.init(from:)),
restSeconds: restSeconds,
doneCountdownSeconds: doneCountdownSeconds,
weightUnit: weightUnit,
editingWorkoutID: editingWorkoutID,
editingSplitID: editingSplitID
)
@@ -0,0 +1,178 @@
//
// WorkoutHealthWriter.swift
// Workouts
//
// Copyright 2025 Rouslan Zenetl. All Rights Reserved.
//
import Foundation
import HealthKit
import SwiftData
/// Writes an *estimated* `HKWorkout` from the phone when a workout completes without
/// a watch session having recorded it so phone-only workouts still feed the Move
/// ring. Mirrors what Apple's own "Add Workout" does: energy MET × bodyweight ×
/// duration, with bodyweight read from Health.
///
/// Dedupe is the whole game: a workout must be written to Health by the watch OR the
/// phone, never both. The signals are `WorkoutMetrics.source`/`healthKitWorkoutUUID`
/// (already present skip) plus a debounce that a late watch update cancels.
@MainActor
final class WorkoutHealthWriter {
private let container: ModelContainer
private let healthStore = HKHealthStore()
private weak var syncEngine: SyncEngine?
/// Scheduled estimate tasks keyed by workout id for debounce + cancellation.
private var pending: [String: Task<Void, Never>] = [:]
/// Grace window before writing, so a watch session that finishes a beat later can
/// cancel us (its metrics arrive over WatchConnectivity and call `watchMetricsArrived`).
private let debounce: Duration = .seconds(10)
/// Default bodyweight when Health has none, in kg (~154 lb).
private let fallbackBodyMassKg = 70.0
init(container: ModelContainer, syncEngine: SyncEngine) {
self.container = container
self.syncEngine = syncEngine
}
private var context: ModelContext { container.mainContext }
private var isScreenshotRun: Bool {
#if DEBUG
return ScreenshotSeed.isActive
#else
return false
#endif
}
/// Request the scopes the estimate needs: share workouts + active energy, read
/// body measurements (to size the estimate) and heart rate (to show watch data).
func authorizeIfNeeded() {
guard HKHealthStore.isHealthDataAvailable(), !isScreenshotRun else { return }
healthStore.requestAuthorization(
toShare: WorkoutHealthAuthorization.phoneShare,
read: WorkoutHealthAuthorization.phoneRead
) { _, _ in }
}
/// A workout was persisted as completed. If nothing has written it to Health yet,
/// schedule an estimated write after the debounce.
func workoutCompleted(_ doc: WorkoutDocument) {
guard HKHealthStore.isHealthDataAvailable(), !isScreenshotRun else { return }
guard doc.status == WorkoutStatus.completed.rawValue, doc.end != nil else { return }
// Already recorded (watch session, or a prior estimate) nothing to do.
guard doc.metrics?.healthKitWorkoutUUID == nil, doc.metrics?.source != .watch else { return }
guard pending[doc.id] == nil else { return }
let id = doc.id
pending[id] = Task { [weak self] in
try? await Task.sleep(for: self?.debounce ?? .seconds(10))
guard let self, !Task.isCancelled else { return }
self.pending[id] = nil
await self.writeEstimate(workoutID: id)
}
}
/// The watch recorded this workout cancel any pending phone estimate so we don't
/// double-write.
func watchMetricsArrived(workoutID id: String) {
pending[id]?.cancel()
pending[id] = nil
}
/// Launch safety sweep: catch workouts that completed but never got a Health record
/// (e.g., the app was killed during the debounce). Bounded to the last day so we
/// don't retroactively flood Health with historical workouts; idempotent via the
/// per-workout UUID guard.
func sweepRecentlyCompleted() {
guard HKHealthStore.isHealthDataAvailable(), !isScreenshotRun else { return }
let cutoff = Date().addingTimeInterval(-24 * 60 * 60)
let completedRaw = WorkoutStatus.completed.rawValue
let all = (try? context.fetch(FetchDescriptor<Workout>())) ?? []
for w in all where w.statusRaw == completedRaw && w.metricHealthKitWorkoutUUID == nil {
guard let end = w.end, end >= cutoff else { continue }
workoutCompleted(WorkoutDocument(from: w))
}
}
// MARK: - Estimate write
private func writeEstimate(workoutID id: String) async {
guard healthStore.authorizationStatus(for: .workoutType()) == .sharingAuthorized else { return }
// Re-read the freshest doc watch metrics may have landed during the debounce.
guard let workout = CacheMapper.fetchWorkout(id: id, in: context),
workout.status == .completed, let end = workout.end else { return }
if let m = workout.metrics, m.healthKitWorkoutUUID != nil || m.source == .watch { return }
let doc = WorkoutDocument(from: workout)
let activity = activityType(for: doc)
let bodyKg = await bodyMassKg()
let hours = max(0, end.timeIntervalSince(doc.start)) / 3600
let kcal = activity.met * bodyKg * hours
let config = HKWorkoutConfiguration()
config.activityType = activity.hkActivityType
config.locationType = .indoor
let builder = HKWorkoutBuilder(healthStore: healthStore, configuration: config, device: .local())
do {
try await builder.beginCollection(at: doc.start)
if kcal > 0 {
let sample = HKQuantitySample(
type: HKQuantityType(.activeEnergyBurned),
quantity: HKQuantity(unit: .kilocalorie(), doubleValue: kcal),
start: doc.start, end: end
)
try await withCheckedThrowingContinuation { (cont: CheckedContinuation<Void, Error>) in
builder.add([sample]) { _, error in
if let error { cont.resume(throwing: error) } else { cont.resume() }
}
}
}
try await builder.endCollection(at: end)
let saved = try await builder.finishWorkout()
// Persist the estimate's metrics so it's never written twice.
var updated = doc
updated.metrics = WorkoutMetrics(
activeEnergyKcal: kcal > 0 ? kcal : nil,
avgHeartRate: nil, maxHeartRate: nil, minHeartRate: nil,
totalVolume: WorkoutVolume.total(doc.logs),
hrZoneSeconds: nil,
healthKitWorkoutUUID: saved?.uuid.uuidString,
source: .phoneEstimate,
recordedAt: end
)
updated.updatedAt = Date()
await syncEngine?.save(workout: updated)
} catch {
// Leave it unmarked; the next launch sweep retries within the window.
}
}
private func activityType(for doc: WorkoutDocument) -> WorkoutActivityType {
if let splitID = doc.splitID, let split = CacheMapper.fetchSplit(id: splitID, in: context) {
return split.activityTypeEnum
}
return .traditionalStrength
}
/// Most recent body mass from Health, in kg, falling back to a default when none.
private func bodyMassKg() async -> Double {
let fallback = fallbackBodyMassKg
return await withCheckedContinuation { continuation in
let sort = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
let query = HKSampleQuery(
sampleType: HKQuantityType(.bodyMass), predicate: nil, limit: 1, sortDescriptors: [sort]
) { _, samples, _ in
let kg = (samples?.first as? HKQuantitySample)?
.quantity.doubleValue(for: .gramUnit(with: .kilo))
continuation.resume(returning: kg ?? fallback)
}
healthStore.execute(query)
}
}
}
+10 -7
View File
@@ -18,23 +18,26 @@ import HealthKit
final class WorkoutLauncher {
private let healthStore = HKHealthStore()
/// Strength/HIIT configuration handed to watchOS; the watch starts a session with
/// the same shape (see `WorkoutSessionManager`).
static func makeConfiguration() -> HKWorkoutConfiguration {
/// Configuration handed to watchOS; the watch starts a session with the same
/// shape (see `WorkoutSessionManager`). The activity type comes from the split so
/// the saved Health workout is categorized correctly.
static func makeConfiguration(activityType: HKWorkoutActivityType) -> HKWorkoutConfiguration {
let configuration = HKWorkoutConfiguration()
configuration.activityType = .traditionalStrengthTraining
configuration.activityType = activityType
configuration.locationType = .indoor
return configuration
}
/// Ask watchOS to launch the Watch app into the workout. Best-effort: no-ops where
/// HealthKit is unavailable (e.g. iPad without it) and silently tolerates a missing
/// or unreachable paired watch.
func launchWatchWorkout() {
/// or unreachable paired watch. Authorization is requested up front by
/// `WorkoutHealthWriter` at launch, so we only need the workout-share scope that
/// `startWatchApp(toHandle:)` itself requires.
func launchWatchWorkout(activityType: HKWorkoutActivityType) {
guard HKHealthStore.isHealthDataAvailable() else { return }
Task {
try? await healthStore.requestAuthorization(toShare: [.workoutType()], read: [])
try? await healthStore.startWatchApp(toHandle: Self.makeConfiguration())
try? await healthStore.startWatchApp(toHandle: Self.makeConfiguration(activityType: activityType))
}
}
}
+2 -2
View File
@@ -25,9 +25,9 @@
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSHealthShareUsageDescription</key>
<string>Workouts uses Health so it can launch your Apple Watch into the session when you start a workout on your iPhone.</string>
<string>Workouts reads your heart rate and body measurements to show workout stats and estimate the calories you burned.</string>
<key>NSHealthUpdateUsageDescription</key>
<string>Workouts uses Health so it can launch your Apple Watch into the session when you start a workout on your iPhone.</string>
<string>Workouts saves your completed sessions to Apple Health (including active energy) so they count toward your Activity rings.</string>
<key>UILaunchScreen</key>
<dict/>
<key>UISupportedInterfaceOrientations</key>
@@ -4,6 +4,9 @@
<dict>
<key>com.apple.developer.healthkit</key>
<true/>
<!-- healthkit.access is for clinical health-records access ONLY. Standard
workout / quantity / characteristic access (what this app uses) needs no
entries here — leave it empty; adding values triggers extra App Review. -->
<key>com.apple.developer.healthkit.access</key>
<array/>
<key>com.apple.developer.icloud-container-identifiers</key>
+7 -5
View File
@@ -12,11 +12,12 @@ enum SplitSeeder {
let weight: Int
}
/// One starter split: visual theme plus its ordered exercises.
/// One starter split: visual theme, activity type, plus its ordered exercises.
private struct SeedSplit {
let name: String
let color: String
let icon: String
let activity: WorkoutActivityType
let exercises: [SeedExercise]
}
@@ -27,17 +28,17 @@ enum SplitSeeder {
/// Starter splits in display order, with sensible machine starting weights.
/// Users adjust weights from the exercise screen.
private static let starterSplits: [SeedSplit] = [
SeedSplit(name: "Upper Body", color: "blue", icon: "figure.strengthtraining.traditional", exercises: [
SeedSplit(name: "Upper Body", color: "blue", icon: "figure.strengthtraining.traditional", activity: .traditionalStrength, exercises: [
SeedExercise(name: "Lat Pull Down", weight: 110),
SeedExercise(name: "Tricep Press", weight: 100),
SeedExercise(name: "Chest Press", weight: 40),
SeedExercise(name: "Seated Row", weight: 90),
]),
SeedSplit(name: "Core", color: "orange", icon: "figure.core.training", exercises: [
SeedSplit(name: "Core", color: "orange", icon: "figure.core.training", activity: .coreTraining, exercises: [
SeedExercise(name: "Abdominal", weight: 0),
SeedExercise(name: "Rotary", weight: 0),
]),
SeedSplit(name: "Lower Body", color: "green", icon: "figure.run", exercises: [
SeedSplit(name: "Lower Body", color: "green", icon: "figure.run", activity: .traditionalStrength, exercises: [
SeedExercise(name: "Abductor", weight: 140),
SeedExercise(name: "Adductor", weight: 140),
SeedExercise(name: "Leg Press", weight: 160),
@@ -59,7 +60,8 @@ enum SplitSeeder {
return SplitDocument(
schemaVersion: SplitDocument.currentSchema, id: ULID.make(),
name: split.name, color: split.color, systemImage: split.icon, order: order,
createdAt: Date(), updatedAt: Date(), exercises: exercises
createdAt: Date(), updatedAt: Date(), exercises: exercises,
activityType: split.activity.rawValue
)
}
}
@@ -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)
}
}