Files
workouts/Workouts/HealthKit/WorkoutLauncher.swift
T
rzen a4ed4df756 Make Apple Health workout recording watch-only
The phone no longer writes estimated Health workouts: the watch, which
runs the live session, is the sole recorder. Replaces WorkoutHealthWriter
with a WorkoutHealthDeleter that only removes a legacy phone-estimate
workout when its record is deleted here, drops the MET calorie table and
the phone's write/read Health scopes, and keeps phoneEstimate decodable
for existing documents.

Claude-Session: https://claude.ai/code/session_01HJDQQDA9QdP8zByg43H5v3
2026-07-08 07:56:19 -04:00

43 lines
1.8 KiB
Swift

//
// WorkoutLauncher.swift
// Workouts
//
// Copyright 2025 Rouslan Zenetl. All Rights Reserved.
//
import Foundation
import HealthKit
/// Launches the companion Watch app into a workout when a session starts on the phone.
///
/// An iPhone app can't foreground its Watch app on its own — the only sanctioned path
/// is HealthKit's `startWatchApp(toHandle:)`, which hands watchOS a workout
/// configuration and brings the Watch app up to run a matching `HKWorkoutSession`.
/// Calling it requires authorization to *share* workouts first.
@MainActor
final class WorkoutLauncher {
private let healthStore = HKHealthStore()
/// 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 = 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. Requests the workout-share scope that
/// `startWatchApp(toHandle:)` itself requires (also enough for a legacy Health delete).
func launchWatchWorkout(activityType: HKWorkoutActivityType) {
guard HKHealthStore.isHealthDataAvailable() else { return }
Task {
try? await healthStore.requestAuthorization(toShare: [.workoutType()], read: [])
try? await healthStore.startWatchApp(toHandle: Self.makeConfiguration(activityType: activityType))
}
}
}