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:
@@ -11,6 +11,7 @@ enum WCPayload {
|
||||
static let workoutKey = "workout"
|
||||
static let restSecondsKey = "restSeconds"
|
||||
static let doneCountdownSecondsKey = "doneCountdownSeconds"
|
||||
static let weightUnitKey = "weightUnit"
|
||||
static let editingWorkoutIDKey = "editingWorkoutID"
|
||||
static let editingSplitIDKey = "editingSplitID"
|
||||
|
||||
@@ -25,12 +26,13 @@ enum WCPayload {
|
||||
/// has a workout's exercise (or a split) open in an editor, the watch parks any
|
||||
/// matching run and locks re-entry, so only one device owns the run at a time. They're
|
||||
/// part of the same latest-wins context — absent keys mean "not editing" (lock clear).
|
||||
static func encodeState(splits: [SplitDocument], workouts: [WorkoutDocument], restSeconds: Int, doneCountdownSeconds: Int, editingWorkoutID: String?, editingSplitID: String?) -> [String: Any] {
|
||||
static func encodeState(splits: [SplitDocument], workouts: [WorkoutDocument], restSeconds: Int, doneCountdownSeconds: Int, weightUnit: String, editingWorkoutID: String?, editingSplitID: String?) -> [String: Any] {
|
||||
var dict: [String: Any] = [:]
|
||||
if let s = try? DocumentCoder.encoder.encode(splits) { dict[splitsKey] = s }
|
||||
if let w = try? DocumentCoder.encoder.encode(workouts) { dict[workoutsKey] = w }
|
||||
dict[restSecondsKey] = restSeconds
|
||||
dict[doneCountdownSecondsKey] = doneCountdownSeconds
|
||||
dict[weightUnitKey] = weightUnit
|
||||
if let editingWorkoutID { dict[editingWorkoutIDKey] = editingWorkoutID }
|
||||
if let editingSplitID { dict[editingSplitIDKey] = editingSplitID }
|
||||
return dict
|
||||
@@ -50,6 +52,8 @@ enum WCPayload {
|
||||
|
||||
static func decodeDoneCountdownSeconds(_ dict: [String: Any]) -> Int? { dict[doneCountdownSecondsKey] as? Int }
|
||||
|
||||
static func decodeWeightUnit(_ dict: [String: Any]) -> String? { dict[weightUnitKey] as? String }
|
||||
|
||||
static func decodeEditingWorkoutID(_ dict: [String: Any]) -> String? { dict[editingWorkoutIDKey] as? String }
|
||||
|
||||
static func decodeEditingSplitID(_ dict: [String: Any]) -> String? { dict[editingSplitIDKey] as? String }
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
//
|
||||
// HealthKitMapping.swift
|
||||
// Workouts (Shared)
|
||||
//
|
||||
// Copyright 2025 Rouslan Zenetl. All Rights Reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import HealthKit
|
||||
|
||||
// Bridges the app's HealthKit-free domain types to HealthKit, and centralizes the
|
||||
// authorization type sets so the watch (which records the session) and the phone
|
||||
// (which writes an estimated workout when no watch ran) request consistent scopes.
|
||||
|
||||
extension WorkoutActivityType {
|
||||
/// The HealthKit activity type used to tag a saved workout, so it lands in the
|
||||
/// right Apple Health / Fitness category and credits the rings appropriately.
|
||||
var hkActivityType: HKWorkoutActivityType {
|
||||
switch self {
|
||||
case .traditionalStrength: .traditionalStrengthTraining
|
||||
case .functionalStrength: .functionalStrengthTraining
|
||||
case .hiit: .highIntensityIntervalTraining
|
||||
case .coreTraining: .coreTraining
|
||||
case .cardio: .mixedCardio
|
||||
case .cycling: .cycling
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Σ sets×reps×weight across weighted logs — the app-native "how much work" number.
|
||||
/// Computed in the stored weight unit (display-only units never change the value).
|
||||
enum WorkoutVolume {
|
||||
static func total(_ logs: [WorkoutLogDocument]) -> Double {
|
||||
logs.reduce(0) { sum, log in
|
||||
guard LoadType(rawValue: log.loadType) == .weight else { return sum }
|
||||
return sum + Double(log.sets * log.reps * log.weight)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The HealthKit scopes each side requests. Kept here so the share/read sets stay in
|
||||
/// sync with what the writers actually use.
|
||||
enum WorkoutHealthAuthorization {
|
||||
/// Watch: records a live session (writes the workout + energy, reads HR/energy back).
|
||||
static let watchShare: Set<HKSampleType> = [
|
||||
.workoutType(),
|
||||
HKQuantityType(.activeEnergyBurned),
|
||||
]
|
||||
static let watchRead: Set<HKObjectType> = [
|
||||
HKQuantityType(.heartRate),
|
||||
HKQuantityType(.activeEnergyBurned),
|
||||
HKCharacteristicType(.dateOfBirth), // → max HR for zone tracking
|
||||
]
|
||||
|
||||
/// Phone: writes an estimated workout when no watch session ran; reads body
|
||||
/// measurements to size the calorie estimate (and HR to display watch data).
|
||||
static let phoneShare: Set<HKSampleType> = [
|
||||
.workoutType(),
|
||||
HKQuantityType(.activeEnergyBurned),
|
||||
]
|
||||
static let phoneRead: Set<HKObjectType> = [
|
||||
HKQuantityType(.bodyMass),
|
||||
HKQuantityType(.heartRate),
|
||||
HKCharacteristicType(.dateOfBirth),
|
||||
HKCharacteristicType(.biologicalSex),
|
||||
]
|
||||
}
|
||||
@@ -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 1→2 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 (low→high)
|
||||
var healthKitWorkoutUUID: String?
|
||||
var source: MetricSource
|
||||
var recordedAt: Date
|
||||
}
|
||||
|
||||
// MARK: - Forward-compatibility gate
|
||||
|
||||
/// A file whose `schemaVersion` exceeds the reader's `currentSchema` was written
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)" }
|
||||
}
|
||||
|
||||
@@ -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>()
|
||||
|
||||
@@ -6,7 +6,8 @@ import SwiftData
|
||||
/// safe; `SyncEngine` repopulates it from the container on next launch.
|
||||
enum WorkoutsModelContainer {
|
||||
/// Bump whenever the cache schema changes — wipes and rebuilds from files.
|
||||
static let currentSchemaVersion = 1
|
||||
/// 2: added health-metric columns to `Workout` and `activityTypeRaw` to `Split`.
|
||||
static let currentSchemaVersion = 2
|
||||
private static let schemaVersionKey = "Workouts.persistenceSchemaVersion"
|
||||
private static let identityTokenKey = "Workouts.iCloudIdentityToken"
|
||||
|
||||
|
||||
Reference in New Issue
Block a user