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:
@@ -72,10 +72,12 @@ struct ActiveWorkoutGateView: View {
|
||||
// Nothing to run yet — pull fresh state in case the phone just started one.
|
||||
if activeWorkouts.isEmpty { bridge.requestSync() }
|
||||
}
|
||||
.onChange(of: activeWorkouts.isEmpty) { _, noActiveWorkouts in
|
||||
// Everything finished (or was cleared) — release the HealthKit session that
|
||||
// was keeping the launched app alive.
|
||||
if noActiveWorkouts { sessionManager.end() }
|
||||
.onChange(of: activeWorkouts.map(\.id)) { previouslyActive, nowActive in
|
||||
// The active list just emptied — the run either completed or was discarded.
|
||||
// Route the HealthKit session accordingly.
|
||||
if nowActive.isEmpty, !previouslyActive.isEmpty {
|
||||
endSession(previouslyActive: previouslyActive)
|
||||
}
|
||||
}
|
||||
// The phone just entered (or left) an editor — if we're inside the now-locked run,
|
||||
// pop back to the gate so re-entry rebuilds a fresh working copy. Also pop if the run
|
||||
@@ -96,6 +98,35 @@ struct ActiveWorkoutGateView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// The active list emptied: decide whether the run completed (save it to Health,
|
||||
/// attach the captured metrics, and forward them to the phone) or was discarded
|
||||
/// (throw the session data away). A completed run stays in the cache as `.completed`;
|
||||
/// a discarded one is tombstoned on the phone and pruned from the cache, so its
|
||||
/// absence from `workouts` is the discard signal.
|
||||
private func endSession(previouslyActive ids: [String]) {
|
||||
let finished = ids
|
||||
.compactMap { id in workouts.first { $0.id == id } }
|
||||
.first { $0.status == .completed }
|
||||
|
||||
guard let finished else {
|
||||
// Nothing survived as completed → the run was discarded. Don't save it.
|
||||
sessionManager.discard()
|
||||
return
|
||||
}
|
||||
|
||||
let doc = WorkoutDocument(from: finished)
|
||||
Task {
|
||||
guard var metrics = await sessionManager.finishAndSave() else { return }
|
||||
metrics.totalVolume = WorkoutVolume.total(doc.logs)
|
||||
var updated = doc
|
||||
updated.metrics = metrics
|
||||
updated.updatedAt = Date()
|
||||
// Carry the captured metrics back to the phone (and thus iCloud) over the
|
||||
// existing workout-update path.
|
||||
bridge.update(workout: updated)
|
||||
}
|
||||
}
|
||||
|
||||
/// If the run we're currently navigated into is no longer available — pruned from the
|
||||
/// cache (discarded/deleted on the phone, or aged out of the pushed set), or locked
|
||||
/// because the phone took over editing it — pop back to the gate.
|
||||
|
||||
Reference in New Issue
Block a user