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:
@@ -176,6 +176,9 @@ final class WatchConnectivityBridge: NSObject {
|
||||
if let done = WCPayload.decodeDoneCountdownSeconds(dict) {
|
||||
UserDefaults.standard.set(done, forKey: WCPayload.doneCountdownSecondsKey)
|
||||
}
|
||||
if let unit = WCPayload.decodeWeightUnit(dict) {
|
||||
UserDefaults.standard.set(unit, forKey: WCPayload.weightUnitKey)
|
||||
}
|
||||
}
|
||||
|
||||
private func applyState(_ splits: [SplitDocument], workouts: [WorkoutDocument]) {
|
||||
@@ -244,12 +247,14 @@ extension WatchConnectivityBridge: WCSessionDelegate {
|
||||
let workouts = WCPayload.decodeWorkouts(applicationContext)
|
||||
let rest = WCPayload.decodeRestSeconds(applicationContext)
|
||||
let done = WCPayload.decodeDoneCountdownSeconds(applicationContext)
|
||||
let unit = WCPayload.decodeWeightUnit(applicationContext)
|
||||
let editingWorkoutID = WCPayload.decodeEditingWorkoutID(applicationContext)
|
||||
let editingSplitID = WCPayload.decodeEditingSplitID(applicationContext)
|
||||
Task { @MainActor in
|
||||
self.applyState(splits, workouts: workouts)
|
||||
if let rest { UserDefaults.standard.set(rest, forKey: WCPayload.restSecondsKey) }
|
||||
if let done { UserDefaults.standard.set(done, forKey: WCPayload.doneCountdownSecondsKey) }
|
||||
if let unit { UserDefaults.standard.set(unit, forKey: WCPayload.weightUnitKey) }
|
||||
// Absent keys mean "not editing" — set unconditionally so the lock clears.
|
||||
self.editingWorkoutID = editingWorkoutID
|
||||
self.editingSplitID = editingSplitID
|
||||
|
||||
@@ -23,9 +23,9 @@
|
||||
<key>ITSAppUsesNonExemptEncryption</key>
|
||||
<false/>
|
||||
<key>NSHealthShareUsageDescription</key>
|
||||
<string>Workouts uses Health to run a workout session on your watch so the app stays active while you train.</string>
|
||||
<string>Workouts reads your heart rate and active energy during a watch workout to show your live stats.</string>
|
||||
<key>NSHealthUpdateUsageDescription</key>
|
||||
<string>Workouts uses Health to run a workout session on your watch so the app stays active while you train.</string>
|
||||
<string>Workouts records your watch workout and saves it to Apple Health (including heart rate and active energy) so it counts toward your Activity rings.</string>
|
||||
<key>WKBackgroundModes</key>
|
||||
<array>
|
||||
<string>workout-processing</string>
|
||||
|
||||
@@ -4,6 +4,9 @@
|
||||
<dict>
|
||||
<key>com.apple.developer.healthkit</key>
|
||||
<true/>
|
||||
<!-- healthkit.access is for clinical health-records access ONLY. The live
|
||||
workout session uses standard workout/quantity access, which needs no
|
||||
entries here — leave it empty. -->
|
||||
<key>com.apple.developer.healthkit.access</key>
|
||||
<array/>
|
||||
</dict>
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -10,6 +10,7 @@ import SwiftData
|
||||
|
||||
struct WorkoutLogListView: View {
|
||||
@Environment(WatchConnectivityBridge.self) private var bridge
|
||||
@Environment(WorkoutSessionManager.self) private var sessionManager
|
||||
@Environment(\.modelContext) private var modelContext
|
||||
|
||||
/// Working copy of the workout. We drive the UI from this and mutate it on
|
||||
@@ -48,6 +49,10 @@ struct WorkoutLogListView: View {
|
||||
|
||||
var body: some View {
|
||||
List {
|
||||
if sessionManager.isRunning {
|
||||
Section { LiveMetricsHUD() }
|
||||
}
|
||||
|
||||
Section(header: Text(label)) {
|
||||
ForEach(sortedLogs) { log in
|
||||
Button {
|
||||
@@ -141,10 +146,41 @@ struct WorkoutLogListView: View {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Live Metrics HUD
|
||||
|
||||
/// Compact live readout (heart rate + active calories) shown while a watch session is
|
||||
/// running. Reads the session manager from the environment itself so its per-second
|
||||
/// updates re-render only this row, not the editable log list above it. Renders
|
||||
/// nothing until the first sample arrives, and dims under Always-On like the timers.
|
||||
private struct LiveMetricsHUD: View {
|
||||
@Environment(WorkoutSessionManager.self) private var sessionManager
|
||||
@Environment(\.isLuminanceReduced) private var dimmed
|
||||
|
||||
var body: some View {
|
||||
let heartRate = sessionManager.currentHeartRate
|
||||
let energy = sessionManager.currentActiveEnergyKcal
|
||||
if heartRate != nil || energy != nil {
|
||||
HStack(spacing: 16) {
|
||||
if let heartRate {
|
||||
Label("\(Int(heartRate.rounded()))", systemImage: "heart.fill")
|
||||
.foregroundStyle(dimmed ? Color.secondary : Color.red)
|
||||
}
|
||||
if let energy {
|
||||
Label("\(Int(energy.rounded())) cal", systemImage: "flame.fill")
|
||||
.foregroundStyle(dimmed ? Color.secondary : Color.orange)
|
||||
}
|
||||
}
|
||||
.font(.caption.monospacedDigit())
|
||||
.frame(maxWidth: .infinity)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Workout Log Row Label
|
||||
|
||||
struct WorkoutLogRowLabel: View {
|
||||
let log: WorkoutLogDocument
|
||||
@AppStorage("weightUnit") private var weightUnit: WeightUnit = .lb
|
||||
|
||||
var body: some View {
|
||||
HStack {
|
||||
@@ -207,7 +243,7 @@ struct WorkoutLogRowLabel: View {
|
||||
return "\(log.sets) × \(secs) sec"
|
||||
}
|
||||
} else {
|
||||
return "\(log.sets) × \(log.reps) × \(log.weight) lbs"
|
||||
return "\(log.sets) × \(log.reps) × \(weightUnit.format(log.weight))"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -219,6 +255,7 @@ struct ExercisePickerView: View {
|
||||
|
||||
let exercises: [Exercise]
|
||||
let onSelect: (Exercise) -> Void
|
||||
@AppStorage("weightUnit") private var weightUnit: WeightUnit = .lb
|
||||
|
||||
var body: some View {
|
||||
NavigationStack {
|
||||
@@ -266,7 +303,7 @@ struct ExercisePickerView: View {
|
||||
return "\(exercise.sets) × \(secs) sec"
|
||||
}
|
||||
} else {
|
||||
return "\(exercise.sets) × \(exercise.reps) × \(exercise.weight) lbs"
|
||||
return "\(exercise.sets) × \(exercise.reps) × \(weightUnit.format(exercise.weight))"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,26 +9,50 @@ import Foundation
|
||||
import HealthKit
|
||||
import Observation
|
||||
|
||||
/// Runs an `HKWorkoutSession` for the duration of a watch workout.
|
||||
/// Runs an `HKWorkoutSession` (with a live builder) for the duration of a watch
|
||||
/// workout.
|
||||
///
|
||||
/// When the phone launches us via `startWatchApp(toHandle:)`, watchOS hands the app
|
||||
/// delegate a workout configuration; starting a session with it is what grants the
|
||||
/// delegate a workout configuration; starting a session with it grants the
|
||||
/// freshly-launched app foreground runtime (and keeps it alive while the wrist is
|
||||
/// down). We don't record samples — the session exists purely to host the UI.
|
||||
/// down). The attached `HKLiveWorkoutBuilder` makes watchOS collect heart rate and
|
||||
/// active energy from the sensors, so finishing the session saves a real `HKWorkout`
|
||||
/// that feeds the Activity rings — and gives us the live HUD values and the metrics
|
||||
/// we send back to the phone.
|
||||
@Observable
|
||||
@MainActor
|
||||
final class WorkoutSessionManager: NSObject {
|
||||
private let healthStore = HKHealthStore()
|
||||
private var session: HKWorkoutSession?
|
||||
private var builder: HKLiveWorkoutBuilder?
|
||||
|
||||
private(set) var isRunning = false
|
||||
|
||||
/// Prompt for workout-sharing authorization. Called once at launch so a later
|
||||
/// phone-initiated launch can start a session without first hitting a permission
|
||||
/// wall.
|
||||
/// Live values for the in-workout HUD. Nil until the first sample arrives (or if
|
||||
/// the corresponding read authorization was denied).
|
||||
private(set) var currentHeartRate: Double?
|
||||
private(set) var currentActiveEnergyKcal: Double?
|
||||
|
||||
/// Seconds accumulated in each of 5 heart-rate zones (low→high). Built on the
|
||||
/// watch because it's the only place with the full HR stream. Empty/ignored when
|
||||
/// the user's age (hence max HR) is unknown.
|
||||
private var hrZoneSeconds = [Double](repeating: 0, count: 5)
|
||||
private var lastHRSampleDate: Date?
|
||||
private var maxHeartRate: Double?
|
||||
|
||||
/// Guards the terminal paths so a late delegate callback can't double-finish.
|
||||
private var isFinishing = false
|
||||
|
||||
/// Prompt for the authorization the live session needs: share workouts + active
|
||||
/// energy (so the session can write them), read heart rate + active energy (to
|
||||
/// surface them), and read date of birth (to derive HR zones). Called once at
|
||||
/// launch so a later phone-initiated launch starts cleanly.
|
||||
func requestAuthorization() {
|
||||
guard HKHealthStore.isHealthDataAvailable() else { return }
|
||||
healthStore.requestAuthorization(toShare: [.workoutType()], read: []) { _, _ in }
|
||||
healthStore.requestAuthorization(
|
||||
toShare: WorkoutHealthAuthorization.watchShare,
|
||||
read: WorkoutHealthAuthorization.watchRead
|
||||
) { _, _ in }
|
||||
}
|
||||
|
||||
/// Start the session for a phone-launched workout. Idempotent — a second launch
|
||||
@@ -37,25 +61,126 @@ final class WorkoutSessionManager: NSObject {
|
||||
guard HKHealthStore.isHealthDataAvailable(), session == nil else { return }
|
||||
do {
|
||||
let session = try HKWorkoutSession(healthStore: healthStore, configuration: configuration)
|
||||
let builder = session.associatedWorkoutBuilder()
|
||||
builder.dataSource = HKLiveWorkoutDataSource(healthStore: healthStore, workoutConfiguration: configuration)
|
||||
session.delegate = self
|
||||
builder.delegate = self
|
||||
self.session = session
|
||||
session.startActivity(with: Date())
|
||||
self.builder = builder
|
||||
|
||||
resetMetricAccumulators()
|
||||
maxHeartRate = computeMaxHeartRate()
|
||||
|
||||
let startDate = Date()
|
||||
session.startActivity(with: startDate)
|
||||
Task { try? await builder.beginCollection(at: startDate) }
|
||||
isRunning = true
|
||||
} catch {
|
||||
session = nil
|
||||
isRunning = false
|
||||
clear()
|
||||
}
|
||||
}
|
||||
|
||||
/// End the session — called when the workout finishes (no active workout remains).
|
||||
func end() {
|
||||
session?.end()
|
||||
/// Finish the session and save it to Health, returning the captured metrics so the
|
||||
/// caller can attach them to the workout and forward to the phone. `totalVolume`
|
||||
/// is left nil here — the caller fills it from the workout's logs.
|
||||
func finishAndSave() async -> WorkoutMetrics? {
|
||||
guard let session, let builder, !isFinishing else { clear(); return nil }
|
||||
isFinishing = true
|
||||
let endDate = Date()
|
||||
session.end()
|
||||
do {
|
||||
try await builder.endCollection(at: endDate)
|
||||
let saved = try await builder.finishWorkout()
|
||||
let metrics = makeMetrics(savedWorkout: saved, endDate: endDate)
|
||||
clear()
|
||||
return metrics
|
||||
} catch {
|
||||
clear()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// End the session and throw the data away — nothing is saved to Health. Used when
|
||||
/// the workout was discarded rather than completed.
|
||||
func discard() {
|
||||
guard let session, let builder, !isFinishing else { clear(); return }
|
||||
isFinishing = true
|
||||
session.end()
|
||||
builder.discardWorkout()
|
||||
clear()
|
||||
}
|
||||
|
||||
// MARK: - Metric helpers
|
||||
|
||||
private func makeMetrics(savedWorkout: HKWorkout?, endDate: Date) -> WorkoutMetrics {
|
||||
let hrUnit = HKUnit.count().unitDivided(by: .minute())
|
||||
let energy = builder?.statistics(for: HKQuantityType(.activeEnergyBurned))?
|
||||
.sumQuantity()?.doubleValue(for: .kilocalorie())
|
||||
let hr = builder?.statistics(for: HKQuantityType(.heartRate))
|
||||
let zones = (maxHeartRate != nil && hrZoneSeconds.contains { $0 > 0 }) ? hrZoneSeconds : nil
|
||||
|
||||
return WorkoutMetrics(
|
||||
activeEnergyKcal: energy,
|
||||
avgHeartRate: hr?.averageQuantity()?.doubleValue(for: hrUnit),
|
||||
maxHeartRate: hr?.maximumQuantity()?.doubleValue(for: hrUnit),
|
||||
minHeartRate: hr?.minimumQuantity()?.doubleValue(for: hrUnit),
|
||||
totalVolume: nil,
|
||||
hrZoneSeconds: zones,
|
||||
healthKitWorkoutUUID: savedWorkout?.uuid.uuidString,
|
||||
source: .watch,
|
||||
recordedAt: endDate
|
||||
)
|
||||
}
|
||||
|
||||
/// Pull the latest live stats off the builder for the HUD, and fold the elapsed
|
||||
/// time into the right HR zone.
|
||||
private func refreshLiveStats() {
|
||||
let hrUnit = HKUnit.count().unitDivided(by: .minute())
|
||||
let newHR = builder?.statistics(for: HKQuantityType(.heartRate))?
|
||||
.mostRecentQuantity()?.doubleValue(for: hrUnit)
|
||||
let now = Date()
|
||||
|
||||
if let maxHeartRate, let prevHR = currentHeartRate, let last = lastHRSampleDate {
|
||||
let dt = now.timeIntervalSince(last)
|
||||
if dt > 0, dt < 60 { hrZoneSeconds[zoneIndex(for: prevHR, maxHR: maxHeartRate)] += dt }
|
||||
}
|
||||
if let newHR { currentHeartRate = newHR }
|
||||
lastHRSampleDate = now
|
||||
|
||||
currentActiveEnergyKcal = builder?.statistics(for: HKQuantityType(.activeEnergyBurned))?
|
||||
.sumQuantity()?.doubleValue(for: .kilocalorie())
|
||||
}
|
||||
|
||||
private func zoneIndex(for hr: Double, maxHR: Double) -> Int {
|
||||
let ratio = hr / maxHR
|
||||
let thresholds = [0.6, 0.7, 0.8, 0.9]
|
||||
return thresholds.reduce(0) { $0 + (ratio >= $1 ? 1 : 0) }
|
||||
}
|
||||
|
||||
/// Max HR ≈ 220 − age, from the user's date of birth. Nil when unavailable (read
|
||||
/// denied or DOB not set), which suppresses zone tracking rather than faking it.
|
||||
private func computeMaxHeartRate() -> Double? {
|
||||
guard let comps = try? healthStore.dateOfBirthComponents(), let birthYear = comps.year else { return nil }
|
||||
let thisYear = Calendar.current.component(.year, from: Date())
|
||||
let age = thisYear - birthYear
|
||||
guard age > 0, age < 120 else { return nil }
|
||||
return Double(220 - age)
|
||||
}
|
||||
|
||||
private func resetMetricAccumulators() {
|
||||
currentHeartRate = nil
|
||||
currentActiveEnergyKcal = nil
|
||||
hrZoneSeconds = [Double](repeating: 0, count: 5)
|
||||
lastHRSampleDate = nil
|
||||
maxHeartRate = nil
|
||||
}
|
||||
|
||||
private func clear() {
|
||||
session = nil
|
||||
builder = nil
|
||||
isRunning = false
|
||||
isFinishing = false
|
||||
resetMetricAccumulators()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,10 +194,22 @@ extension WorkoutSessionManager: HKWorkoutSessionDelegate {
|
||||
date: Date
|
||||
) {
|
||||
guard toState == .ended || toState == .stopped else { return }
|
||||
Task { @MainActor in self.clear() }
|
||||
// Only reset if we didn't drive the end ourselves (finishAndSave/discard set
|
||||
// `isFinishing` and clear on their own); this catches system-ended sessions.
|
||||
Task { @MainActor in if !self.isFinishing { self.clear() } }
|
||||
}
|
||||
|
||||
nonisolated func workoutSession(_ workoutSession: HKWorkoutSession, didFailWithError error: Error) {
|
||||
Task { @MainActor in self.clear() }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - HKLiveWorkoutBuilderDelegate
|
||||
|
||||
extension WorkoutSessionManager: HKLiveWorkoutBuilderDelegate {
|
||||
nonisolated func workoutBuilder(_ workoutBuilder: HKLiveWorkoutBuilder, didCollectDataOf collectedTypes: Set<HKSampleType>) {
|
||||
Task { @MainActor in self.refreshLiveStats() }
|
||||
}
|
||||
|
||||
nonisolated func workoutBuilderDidCollectEvent(_ workoutBuilder: HKLiveWorkoutBuilder) {}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user