import Foundation import HealthKit import CoreLocation // HealthKitWorkoutSource.swift // Reads your real runs from Apple Health. Read-only: RunLog never writes to Health. // // Privacy note: iOS never tells an app whether you said "no" to reading data. // If access was refused, Health simply returns nothing — so the app shows // "No runs found" with a hint to check Settings, instead of an error. @MainActor final class HealthKitWorkoutSource: WorkoutSource { private let store = HKHealthStore() private var workoutsByID: [UUID: HKWorkout] = [:] let isSampleData = false var isAvailable: Bool { HKHealthStore.isHealthDataAvailable() } /// Everything RunLog asks permission to read. private var readTypes: Set { [ HKObjectType.workoutType(), // the runs themselves HKSeriesType.workoutRoute(), // GPS routes HKQuantityType(.heartRate), HKQuantityType(.activeEnergyBurned), HKQuantityType(.distanceWalkingRunning), HKQuantityType(.stepCount), // for cadence (步频) ] } func requestAccess() async throws { try await store.requestAuthorization(toShare: [], read: readTypes) } // MARK: Runs list func fetchRuns() async throws -> [Run] { let query = HKSampleQueryDescriptor( predicates: [.workout(HKQuery.predicateForWorkouts(with: .running))], sortDescriptors: [SortDescriptor(\.startDate, order: .reverse)] ) let workouts = try await query.result(for: store) workoutsByID = Dictionary(workouts.map { ($0.uuid, $0) }, uniquingKeysWith: { first, _ in first }) return workouts.map { makeRun(from: $0) } } /// Converts one Health workout into RunLog's simple Run shape. private func makeRun(from workout: HKWorkout) -> Run { let bpm = HKUnit.count().unitDivided(by: .minute()) let heartRate = workout.statistics(for: HKQuantityType(.heartRate)) let distance = workout.statistics(for: HKQuantityType(.distanceWalkingRunning))? .sumQuantity()?.doubleValue(for: .meter()) let calories = workout.statistics(for: HKQuantityType(.activeEnergyBurned))? .sumQuantity()?.doubleValue(for: .kilocalorie()) let climb = (workout.metadata?[HKMetadataKeyElevationAscended] as? HKQuantity)? .doubleValue(for: .meter()) let indoor = (workout.metadata?[HKMetadataKeyIndoorWorkout] as? Bool) ?? false return Run( id: workout.uuid, startDate: workout.startDate, endDate: workout.endDate, duration: workout.duration, distanceMeters: distance, averageHeartRate: heartRate?.averageQuantity()?.doubleValue(for: bpm), maxHeartRate: heartRate?.maximumQuantity()?.doubleValue(for: bpm), activeCalories: calories, elevationGainMeters: climb, isIndoor: indoor, sourceName: workout.sourceRevision.source.name ) } // MARK: One run's details func fetchDetails(for run: Run) async throws -> RunDetails { guard let workout = workoutsByID[run.id] else { return RunDetails(route: [], totalSteps: nil) } let route = try await fetchRoute(for: workout) let steps = try await fetchSteps(for: workout) return RunDetails(route: route, totalSteps: steps) } /// The GPS points saved with this workout (empty for indoor runs or runs without GPS). private func fetchRoute(for workout: HKWorkout) async throws -> [RoutePoint] { let routeQuery = HKSampleQueryDescriptor( predicates: [.workoutRoute(HKQuery.predicateForObjects(from: workout))], sortDescriptors: [] ) let routes = try await routeQuery.result(for: store) var points: [RoutePoint] = [] for route in routes { // Health hands the GPS points over in batches; collect them all. for try await location in HKWorkoutRouteQueryDescriptor(route).results(for: store) { points.append(RoutePoint(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude, altitude: location.altitude, timestamp: location.timestamp)) } } return points.sorted { $0.timestamp < $1.timestamp } } /// Total steps during the run. The Watch saves step counts while you run; /// cadence = these steps ÷ minutes. If the workout already has a step total /// we use it, otherwise we add up the steps between start and end /// (Health removes double-counting if your iPhone also counted steps). private func fetchSteps(for workout: HKWorkout) async throws -> Double? { let stepType = HKQuantityType(.stepCount) if let total = workout.statistics(for: stepType)?.sumQuantity() { return total.doubleValue(for: .count()) } let duringRun = HKQuery.predicateForSamples(withStart: workout.startDate, end: workout.endDate, options: []) let query = HKStatisticsQueryDescriptor( predicate: .quantitySample(type: stepType, predicate: duringRun), options: .cumulativeSum ) return try await query.result(for: store)?.sumQuantity()?.doubleValue(for: .count()) } }