RunLog code
Stage 1 + 2 Swift files, ready to drop into the RunLog Xcode project. Open this page on the Mac, download, then drag the files into Xcode.
Updated 2026-11-29 11:27 (Singapore time). If this time is older than expected, the latest deploy hasn’t gone live yet: reload the page.
ContentView.swift
Replaces Xcode’s file
First screen: decides between welcome, loading, runs list, or a problem message. 138 lines
import SwiftUI
// ContentView.swift (REPLACES the ContentView.swift Xcode created)
// The app's first screen. It decides what to show:
// connect-to-Health screen, loading, the runs list, or a problem message.
/// Keeps track of the runs list and where we are (connecting, loading, done…).
@MainActor
@Observable
final class RunListModel {
enum Phase {
case notConnected // first launch: show the welcome / connect screen
case loading
case loaded
case healthUnavailable // this device has no Apple Health
case failed(String)
}
var phase: Phase = .loading
var runs: [Run] = []
let source: any WorkoutSource
private static let connectedKey = "hasConnectedHealth"
init(source: any WorkoutSource) {
self.source = source
}
/// Called once when the app opens.
func start() async {
guard source.isAvailable else { phase = .healthUnavailable; return }
if source.isSampleData || UserDefaults.standard.bool(forKey: Self.connectedKey) {
await connect()
} else {
phase = .notConnected
}
}
/// Asks for Health permission (Apple shows its sheet only the first time), then loads runs.
func connect() async {
phase = .loading
do {
try await source.requestAccess()
UserDefaults.standard.set(true, forKey: Self.connectedKey)
await reload()
} catch {
phase = .failed(error.localizedDescription)
}
}
/// Reads the runs again (also used by pull-to-refresh).
func reload() async {
do {
runs = try await source.fetchRuns()
phase = .loaded
} catch {
phase = .failed(error.localizedDescription)
}
}
/// Quietly re-reads the runs when you come back to the app (e.g. after the
/// Watch synced a new run). Keeps the current list if anything goes wrong.
func refreshIfLoaded() async {
guard case .loaded = phase else { return }
if let fresh = try? await source.fetchRuns() {
runs = fresh
}
}
}
struct ContentView: View {
@State private var model = RunListModel(source: ContentView.makeSource())
@Environment(\.scenePhase) private var scenePhase // tells us when the app comes back on screen
var body: some View {
NavigationStack {
switch model.phase {
case .notConnected:
ConnectHealthView {
Task { await model.connect() }
}
case .loading:
ProgressView("Reading your runs…")
case .healthUnavailable:
ContentUnavailableView(
"Apple Health isn't available",
systemImage: "heart.slash",
description: Text("RunLog needs an iPhone with the Health app.")
)
case .failed(let message):
ContentUnavailableView {
Label("Couldn't read your runs", systemImage: "exclamationmark.triangle")
} description: {
Text(message)
} actions: {
Button("Try again") { Task { await model.connect() } }
}
case .loaded:
if model.runs.isEmpty {
NoRunsView {
Task { await model.reload() }
}
} else {
RunListView(runs: model.runs, source: model.source) {
await model.reload()
}
}
}
}
.tint(Color.lane)
.task { await model.start() }
.onChange(of: scenePhase) { _, newPhase in
// Switching back to RunLog → pick up runs the Watch synced meanwhile.
if newPhase == .active {
Task { await model.refreshIfLoaded() }
}
}
}
/// Real Health data on a real iPhone; sample runs in the simulator (it has no Watch data).
static func makeSource() -> any WorkoutSource {
#if targetEnvironment(simulator)
return SampleWorkoutSource()
#else
return HealthKitWorkoutSource()
#endif
}
}
extension Color {
/// RunLog's accent colour: Apple's indigo, which adjusts itself for dark mode.
static var lane: Color { .indigo }
}
#Preview {
ContentView()
}
RunListView.swift
New file
Runs list grouped by month, the welcome screen, and the “no runs found” screen. 181 lines
import SwiftUI
// RunListView.swift
// The runs list (grouped by month), plus the welcome screen and the
// "no runs found" screen.
struct RunListView: View {
let runs: [Run] // newest first
let source: any WorkoutSource
let onRefresh: @MainActor () async -> Void
var body: some View {
List {
if source.isSampleData {
Section {
Text("Sample runs (simulator only). On your iPhone, RunLog shows your real runs from Health.")
.font(.footnote)
.foregroundStyle(.secondary)
}
}
ForEach(monthGroups) { group in
Section(group.title) {
ForEach(group.runs) { run in
NavigationLink {
RunDetailView(run: run, source: source)
} label: {
RunRow(run: run)
}
}
}
}
}
.navigationTitle("RunLog")
.refreshable { await onRefresh() }
}
/// Runs grouped under "November 2026", "October 2026", …
private var monthGroups: [MonthGroup] {
var groups: [MonthGroup] = []
for run in runs {
let title = run.startDate.formatted(.dateTime.month(.wide).year())
if groups.last?.title == title {
groups[groups.count - 1].runs.append(run)
} else {
groups.append(MonthGroup(title: title, runs: [run]))
}
}
return groups
}
}
private struct MonthGroup: Identifiable {
let title: String
var runs: [Run]
var id: String { title }
}
/// One line in the list: day, distance (big), time and pace.
struct RunRow: View {
let run: Run
var body: some View {
HStack(spacing: 14) {
VStack(spacing: 2) {
Text(run.startDate, format: .dateTime.day())
.font(.title2.weight(.semibold))
.fontWidth(.condensed)
Text(run.startDate, format: .dateTime.weekday(.abbreviated))
.font(.caption)
.foregroundStyle(.secondary)
}
.frame(width: 44)
VStack(alignment: .leading, spacing: 4) {
if let meters = run.distanceMeters {
HStack(alignment: .firstTextBaseline, spacing: 3) {
Text(RunFormat.kilometres(meters))
.font(.system(size: 30, weight: .bold))
.fontWidth(.condensed)
Text("km")
.font(.subheadline.weight(.semibold))
.foregroundStyle(.secondary)
}
}
HStack(spacing: 12) {
Text(RunFormat.duration(run.duration))
if let pace = run.paceSecondsPerKm {
Text("\(RunFormat.pace(pace)) /km")
}
}
.font(.subheadline)
.foregroundStyle(.secondary)
.monospacedDigit()
}
Spacer(minLength: 0)
if run.isIndoor {
Text("Indoor")
.font(.caption)
.foregroundStyle(.secondary)
.padding(.horizontal, 6)
.padding(.vertical, 2)
.overlay(RoundedRectangle(cornerRadius: 6).stroke(.quaternary))
}
}
.padding(.vertical, 4)
}
}
/// First-launch screen: explains what RunLog reads, then asks for Health access.
struct ConnectHealthView: View {
let onConnect: () -> Void
var body: some View {
VStack(spacing: 0) {
Spacer()
Image(systemName: "figure.run")
.font(.system(size: 44, weight: .semibold))
.foregroundStyle(.white)
.frame(width: 84, height: 84)
.background(Color.lane, in: RoundedRectangle(cornerRadius: 20, style: .continuous))
Text("Welcome to RunLog")
.font(.largeTitle.bold())
.padding(.top, 22)
Text("Your running, your story.")
.font(.title3)
.foregroundStyle(.secondary)
.padding(.top, 6)
VStack(alignment: .leading, spacing: 14) {
Label("Reads the runs your Apple Watch saves to Health: distance, time, heart rate, steps and route.",
systemImage: "heart.text.square")
Label("Everything stays on this iPhone. Nothing is uploaded.", systemImage: "lock")
Label("RunLog never changes your Health data.", systemImage: "hand.raised")
}
.font(.callout)
.foregroundStyle(.secondary)
.padding(.top, 28)
Spacer()
Button(action: onConnect) {
Text("Connect to Apple Health")
.font(.headline)
.frame(maxWidth: .infinity)
.padding(.vertical, 6)
}
.buttonStyle(.borderedProminent)
.controlSize(.large)
Text("Next, iOS asks which data to share. Turn on all of them for the full picture.")
.font(.footnote)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
.padding(.top, 12)
}
.padding(24)
}
}
/// Shown when Health returned no runs — often because access was turned off.
struct NoRunsView: View {
let onCheckAgain: () -> Void
var body: some View {
ContentUnavailableView {
Label("No runs found", systemImage: "figure.run")
} description: {
Text("RunLog shows running workouts saved in Health. If you have runs but see none, RunLog may not have permission: open Settings › Health › Data Access & Devices › RunLog and turn on all categories.")
} actions: {
Button("Check again", action: onCheckAgain)
}
.navigationTitle("RunLog")
}
}
#Preview("Welcome") {
ConnectHealthView {}
}
RunDetailView.swift
New file
One run: route map, big distance, stats grid (pace, heart rate, cadence…). 260 lines
import SwiftUI
import MapKit
// RunDetailView.swift
// One run: date, route map, big distance, and a grid of stats.
// Only numbers Health actually recorded are shown; anything missing is
// listed at the bottom as "Not recorded for this run".
struct RunDetailView: View {
let run: Run
let source: any WorkoutSource
@State private var details: RunDetails?
@State private var loadFailed = false
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 0) {
header
routeSection
.padding(.top, 14)
if let meters = run.distanceMeters {
HStack(alignment: .firstTextBaseline, spacing: 4) {
Text(RunFormat.kilometres(meters))
.font(.system(size: 76, weight: .bold))
.fontWidth(.condensed)
Text("km")
.font(.title2.weight(.semibold))
.foregroundStyle(.secondary)
}
.padding(.top, 20)
.padding(.horizontal, 4)
}
StatGrid(tiles: tiles)
.padding(.top, 12)
footnotes
.padding(.top, 14)
.padding(.horizontal, 4)
}
.padding(.horizontal, 16)
.padding(.bottom, 32)
}
.background(Color(.systemGroupedBackground))
.navigationTitle(run.startDate.formatted(.dateTime.day().month()))
.navigationBarTitleDisplayMode(.inline)
.task { await loadDetails() }
}
private func loadDetails() async {
guard details == nil else { return }
do {
details = try await source.fetchDetails(for: run)
} catch {
loadFailed = true
}
}
// MARK: Pieces
private var header: some View {
VStack(alignment: .leading, spacing: 2) {
Text(run.startDate.formatted(.dateTime.weekday(.abbreviated).day().month(.wide).year()))
.font(.title2.bold())
Text("\(run.isIndoor ? "Indoor run" : "Outdoor run"), started \(run.startDate.formatted(date: .omitted, time: .shortened))")
.foregroundStyle(.secondary)
}
.padding(.horizontal, 4)
.padding(.top, 8)
}
@ViewBuilder
private var routeSection: some View {
if let details {
if details.route.count >= 2 {
RouteMapView(points: details.route)
.frame(height: 240)
.clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
} else {
MessageCard(title: "No route for this run",
text: run.isIndoor ? "Indoor runs don't record GPS." : "This run was saved without GPS.")
}
} else if loadFailed {
MessageCard(title: "Couldn't load the route",
text: "Go back and open this run again.")
} else {
RoundedRectangle(cornerRadius: 16, style: .continuous)
.fill(Color(.secondarySystemGroupedBackground))
.frame(height: 240)
.overlay(ProgressView())
}
}
private var cadence: Double? {
details?.cadence(duration: run.duration)
}
private var tiles: [StatTile] {
var tiles = [StatTile(label: "Duration", value: RunFormat.duration(run.duration))]
if let pace = run.paceSecondsPerKm {
tiles.append(StatTile(label: "Avg pace", value: RunFormat.pace(pace), unit: "/km"))
}
if let hr = run.averageHeartRate {
tiles.append(StatTile(label: "Avg heart rate", value: RunFormat.whole(hr), unit: "bpm", dot: .pink))
}
if let hr = run.maxHeartRate {
tiles.append(StatTile(label: "Max heart rate", value: RunFormat.whole(hr), unit: "bpm", dot: .pink))
}
if let cadence {
tiles.append(StatTile(label: "Cadence", value: RunFormat.whole(cadence), unit: "spm", dot: .teal))
} else if details == nil && !loadFailed {
tiles.append(StatTile(label: "Cadence", value: "…", dot: .teal)) // still loading
}
if let kcal = run.activeCalories {
tiles.append(StatTile(label: "Active calories", value: RunFormat.whole(kcal), unit: "kcal"))
}
if let climb = run.elevationGainMeters {
tiles.append(StatTile(label: "Elevation gain", value: RunFormat.whole(climb), unit: "m"))
}
return tiles
}
private var footnotes: some View {
VStack(alignment: .leading, spacing: 6) {
Text("Recorded by \(run.sourceName)")
if !missing.isEmpty {
Text("Not recorded for this run: \(missing.joined(separator: ", ")).")
.foregroundStyle(.tertiary)
}
}
.font(.footnote)
.foregroundStyle(.secondary)
}
private var missing: [String] {
var list: [String] = []
if run.averageHeartRate == nil { list.append("heart rate") }
if details != nil && cadence == nil { list.append("cadence") }
if run.activeCalories == nil { list.append("calories") }
return list
}
}
// MARK: - Route map
/// The route as a line on an Apple Map, with a green start dot and a dark finish dot.
struct RouteMapView: View {
let points: [RoutePoint]
var body: some View {
let coordinates = points.map { $0.coordinate }
Map(initialPosition: .automatic) {
MapPolyline(coordinates: coordinates)
.stroke(Color.lane, style: StrokeStyle(lineWidth: 5, lineCap: .round, lineJoin: .round))
if let start = coordinates.first {
Annotation("Start", coordinate: start, anchor: .center) {
EndDot(color: .green)
}
.annotationTitles(.hidden)
}
if let finish = coordinates.last {
Annotation("Finish", coordinate: finish, anchor: .center) {
EndDot(color: .black)
}
.annotationTitles(.hidden)
}
}
.mapStyle(.standard(elevation: .flat, pointsOfInterest: .excludingAll))
}
}
private struct EndDot: View {
let color: Color
var body: some View {
Circle()
.fill(color)
.frame(width: 14, height: 14)
.overlay(Circle().stroke(.white, lineWidth: 2.5))
}
}
// MARK: - Stats grid
struct StatTile: Identifiable {
let label: String
let value: String
var unit: String? = nil
var dot: Color? = nil
var id: String { label }
}
/// Two columns of stats on one card, separated by hairlines.
struct StatGrid: View {
let tiles: [StatTile]
var body: some View {
let columns = [GridItem(.flexible(), spacing: 0.5), GridItem(.flexible(), spacing: 0.5)]
LazyVGrid(columns: columns, spacing: 0.5) {
ForEach(tiles) { tile in
StatCell(tile: tile)
}
if tiles.count % 2 == 1 {
StatCell(tile: StatTile(label: " ", value: " ")) // blank cell keeps the card even
}
}
.background(Color(.separator))
.clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))
}
}
private struct StatCell: View {
let tile: StatTile
var body: some View {
VStack(alignment: .leading, spacing: 2) {
HStack(spacing: 5) {
if let dot = tile.dot {
Circle().fill(dot).frame(width: 7, height: 7)
}
Text(tile.label)
}
.font(.footnote)
.foregroundStyle(.secondary)
HStack(alignment: .firstTextBaseline, spacing: 2) {
Text(tile.value)
.font(.title2.weight(.semibold))
.fontWidth(.condensed)
.monospacedDigit()
if let unit = tile.unit {
Text(unit)
.font(.subheadline)
.foregroundStyle(.secondary)
}
}
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal, 16)
.padding(.vertical, 14)
.background(Color(.secondarySystemGroupedBackground))
}
}
/// A rounded card with a short message (e.g. "No route for this run").
private struct MessageCard: View {
let title: String
let text: String
var body: some View {
VStack(spacing: 4) {
Text(title).font(.headline)
Text(text).foregroundStyle(.secondary)
}
.frame(maxWidth: .infinity)
.padding(.vertical, 22)
.padding(.horizontal, 18)
.background(Color(.secondarySystemGroupedBackground),
in: RoundedRectangle(cornerRadius: 16, style: .continuous))
}
}
RunLog’s own simple data shapes: Run, RoutePoint, RunDetails. 52 lines
import Foundation
import CoreLocation
// Models.swift
// RunLog's own simple data shapes. The screens only ever see these —
// never Apple Health's own types — so screens stay simple and the data
// source can be swapped (real Health data on the iPhone, sample data in
// the simulator, maybe a RunLog Watch app one day).
/// One run. Anything Health didn't record is nil and is hidden on screen.
struct Run: Identifiable {
let id: UUID
let startDate: Date
let endDate: Date
let duration: TimeInterval // active running time in seconds (pauses not counted)
let distanceMeters: Double?
let averageHeartRate: Double? // beats per minute
let maxHeartRate: Double? // beats per minute
let activeCalories: Double? // kcal
let elevationGainMeters: Double?
let isIndoor: Bool
let sourceName: String // which app/device saved it, e.g. "Apple Watch" or "Strava"
/// Average pace in seconds per km, or nil if there's no usable distance.
var paceSecondsPerKm: Double? {
RunMath.pace(seconds: duration, meters: distanceMeters)
}
}
/// One GPS point along the route.
struct RoutePoint {
let latitude: Double
let longitude: Double
let altitude: Double // metres above sea level
let timestamp: Date
var coordinate: CLLocationCoordinate2D {
CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
}
/// The heavier data for one run, loaded only when you open that run.
struct RunDetails {
let route: [RoutePoint] // empty = no GPS route for this run
let totalSteps: Double? // nil = no step data, so no cadence
/// Average cadence (步频) in steps per minute.
func cadence(duration: TimeInterval) -> Double? {
RunMath.cadence(steps: totalSteps, seconds: duration)
}
}
Formatters.swift
New file
Pace / time / distance text and the cadence + pace maths. 62 lines
import Foundation
// Formatters.swift
// Small, pure helpers: the maths and the text formatting for run numbers.
// No Apple Health or screen code here, so these rules are easy to check.
// (The web mockup uses exactly the same rules.)
/// Calculations made from what Health recorded. Each one returns nil when the
/// input is missing or too small to give a meaningful answer — we never guess.
enum RunMath {
/// Average pace in seconds per kilometre, e.g. 313.4 (= 5'13" per km).
static func pace(seconds: TimeInterval, meters: Double?) -> Double? {
guard let meters, meters >= 10, seconds > 0 else { return nil }
return seconds / (meters / 1000)
}
/// Cadence (步频) in steps per minute: total steps ÷ minutes running.
static func cadence(steps: Double?, seconds: TimeInterval) -> Double? {
guard let steps, steps > 0, seconds >= 60 else { return nil }
return steps / (seconds / 60)
}
}
/// Turns numbers into the text shown on screen.
enum RunFormat {
/// 313.4 seconds per km -> 5'13"
static func pace(_ secondsPerKm: Double) -> String {
let total = Int(secondsPerKm.rounded())
let minutes = total / 60
let seconds = total % 60
return "\(minutes)'" + twoDigits(seconds) + "\""
}
/// 3134 seconds -> 52:14, 3725 seconds -> 1:02:05
static func duration(_ seconds: TimeInterval) -> String {
let total = Int(seconds.rounded())
let hours = total / 3600
let minutes = (total % 3600) / 60
let secs = total % 60
if hours > 0 {
return "\(hours):" + twoDigits(minutes) + ":" + twoDigits(secs)
}
return "\(minutes):" + twoDigits(secs)
}
/// 10020 metres -> "10.02" (the screen adds the "km" label separately)
static func kilometres(_ meters: Double) -> String {
String(format: "%.2f", meters / 1000)
}
/// 151.6 -> "152" (heart rate, cadence, calories, metres of climb)
static func whole(_ value: Double) -> String {
String(Int(value.rounded()))
}
private static func twoDigits(_ value: Int) -> String {
value < 10 ? "0\(value)" : "\(value)"
}
}
WorkoutSource.swift
New file
The data-source rules, plus sample runs used only in the simulator. 98 lines
import Foundation
// WorkoutSource.swift
// The "workout source" layer: one list of jobs that any data source must do.
// - HealthKitWorkoutSource (other file) = your real runs from Apple Health, used on the iPhone.
// - SampleWorkoutSource (below) = made-up runs, used ONLY in the simulator,
// because the simulator has no Apple Watch data. The app labels them as samples.
@MainActor
protocol WorkoutSource {
/// False on devices without Apple Health (e.g. some iPads).
var isAvailable: Bool { get }
/// True only for the made-up simulator data.
var isSampleData: Bool { get }
/// Shows Apple's "allow RunLog to read…" sheet (only the first time).
func requestAccess() async throws
/// All running workouts, newest first.
func fetchRuns() async throws -> [Run]
/// Route + steps for one run (loaded when you open it).
func fetchDetails(for run: Run) async throws -> RunDetails
}
// MARK: - Sample data (simulator only)
@MainActor
final class SampleWorkoutSource: WorkoutSource {
let isAvailable = true
let isSampleData = true
private var detailsByID: [UUID: RunDetails] = [:]
func requestAccess() async throws {}
func fetchRuns() async throws -> [Run] {
try await Task.sleep(for: .milliseconds(400)) // pretend to load, so the loading screen can be seen
// (days ago, start hour, km, seconds, avg HR, max HR, kcal, steps, climb m, indoor)
let samples: [(Int, Int, Double, Double, Double?, Double?, Double?, Double?, Double?, Bool)] = [
(1, 7, 10.02, 3134, 152, 171, 642, 8960, 58, false),
(3, 19, 5.21, 1650, 147, 163, 331, 4720, 21, false),
(6, 6, 15.40, 5262, 149, 168, 985, 14650, 96, false),
(9, 20, 6.00, 2100, 139, 151, 368, 5940, nil, true),
(12, 7, 8.05, 2611, 150, 166, 512, 7310, 40, false),
(30, 6, 21.10, 7712, 156, 178, 1390, 20110, 133, false),
(34, 18, 4.98, 1622, nil, nil, nil, nil, nil, false),
]
let calendar = Calendar.current
let today = calendar.startOfDay(for: .now)
var runs: [Run] = []
for s in samples {
let day = calendar.date(byAdding: .day, value: -s.0, to: today) ?? today
let start = calendar.date(byAdding: .hour, value: s.1, to: day) ?? day
let run = Run(
id: UUID(),
startDate: start,
endDate: start.addingTimeInterval(s.3),
duration: s.3,
distanceMeters: s.2 * 1000,
averageHeartRate: s.4,
maxHeartRate: s.5,
activeCalories: s.6,
elevationGainMeters: s.8,
isIndoor: s.9,
sourceName: s.4 == nil ? "Sample app" : "Apple Watch (sample)"
)
detailsByID[run.id] = RunDetails(
route: s.9 ? [] : Self.loopRoute(start: start, duration: s.3, kilometres: s.2),
totalSteps: s.7
)
runs.append(run)
}
return runs
}
func fetchDetails(for run: Run) async throws -> RunDetails {
try await Task.sleep(for: .milliseconds(300))
return detailsByID[run.id] ?? RunDetails(route: [], totalSteps: nil)
}
/// A wobbly loop around Marina Bay, Singapore, roughly the run's length.
private static func loopRoute(start: Date, duration: TimeInterval, kilometres: Double) -> [RoutePoint] {
let centerLat = 1.2840, centerLon = 103.8590
let radiusKm = kilometres / (2 * Double.pi)
let count = 240
return (0..<count).map { i in
let t = Double(i) / Double(count - 1) * 2 * Double.pi
let r = radiusKm * (1 + 0.12 * sin(5 * t))
let lat = centerLat + (r / 111.0) * sin(t)
let lon = centerLon + (r / (111.0 * cos(centerLat * Double.pi / 180))) * cos(t)
return RoutePoint(latitude: lat, longitude: lon, altitude: 5,
timestamp: start.addingTimeInterval(duration * Double(i) / Double(count - 1)))
}
}
}
HealthKitWorkoutSource.swift
New file
Reads your real runs, routes and steps from Apple Health (read-only). 126 lines
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> {
[
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())
}
}