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) } } } struct ContentView: View { @State private var model = RunListModel(source: ContentView.makeSource()) 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() } } /// 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() }