SPB Git

Repository Public License

StepMissionView.swift 11.7 KB 252 lines swift

1// ORIX Alarm2// File: App/Features/Missions/StepMissionView.swift3// Description: Step Challenge mission: walk a number of steps counted by the system pedometer, with honest handling of permission and unsupported devices.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import CoreMotion9import SwiftUI1011/// Thin wrapper around `CMPedometer`. Its callbacks arrive on a private queue, so it lives outside the main actor.12nonisolated final class StepCounter: @unchecked Sendable {13    enum Failure: Error, Sendable { case notAuthorized, other }14    private let pedometer = CMPedometer()15    /// Only touched from the main actor (start and stop are called by the view).16    private var running = false1718    /// The simulator has no motion hardware even though the API can report otherwise there.19    static var isAvailable: Bool {20        #if targetEnvironment(simulator)21        false22        #else23        CMPedometer.isStepCountingAvailable()24        #endif25    }26    static var authorization: CMAuthorizationStatus { CMPedometer.authorizationStatus() }2728    /// Reports the cumulative number of steps since `date`.29    func start(from date: Date, onUpdate: @escaping @Sendable (Result<Int, Failure>) -> Void) {30        running = true31        pedometer.startUpdates(from: date) { data, error in32            if let error = error as NSError? {33                let denied = error.domain == CMErrorDomain && (error.code == Int(CMErrorMotionActivityNotAuthorized.rawValue) || error.code == Int(CMErrorMotionActivityNotEntitled.rawValue))34                onUpdate(.failure(denied ? .notAuthorized : .other))35            } else if let data {36                onUpdate(.success(data.numberOfSteps.intValue))37            }38        }39    }4041    /// Does nothing unless updates were started: any pedometer call, even a stop, can raise the system permission prompt.42    func stop() {43        guard running else { return }44        running = false45        pedometer.stopUpdates()46    }47}4849struct StepMissionView: View {50    let mission: ResolvedMission51    let onFinish: (MissionOutcome) -> Void52    @Environment(\.accessibilityReduceMotion) private var reduceMotion53    @Environment(\.openURL) private var openURL5455    private enum Phase: Equatable { case explain, counting, denied, restricted, unsupported, failed, done }56    @State private var phase: Phase = .explain57    @State private var challenge: StepChallenge58    @State private var counter = StepCounter()59    @State private var started = Date()60    @State private var finished = false61    @State private var simulated = false6263    init(mission: ResolvedMission, onFinish: @escaping (MissionOutcome) -> Void) {64        self.mission = mission; self.onFinish = onFinish65        _challenge = State(initialValue: StepChallenge(goal: mission.step.stepGoal))66    }6768    /// `-ORIXFakeSteps YES`, DEBUG builds only.69    private static var fakeSteps: Bool {70        #if DEBUG71        UserDefaults.standard.bool(forKey: "ORIXFakeSteps")72        #else73        false74        #endif75    }7677    var body: some View {78        MissionScaffold(instruction: String(localized: "Get up and walk \(challenge.goal) steps.")) {79            switch phase {80            case .explain:81                notice(symbol: "figure.walk.motion", tint: Theme.success, title: "Motion access",82                       text: "ORIX Alarm asks the iPhone's pedometer for your step count during this mission. Motion data stays on this iPhone.") {83                    Button("Start counting") { startCounting() }.buttonStyle(PrimaryButtonStyle()).accessibilityIdentifier("steps.start")84                }85            case .counting, .done: counting86            case .denied:87                notice(symbol: "figure.walk.motion.trianglebadge.exclamationmark", tint: Theme.gold, title: "Motion access is off",88                       text: "Steps cannot be counted. To use this mission, open Settings, choose ORIX Alarm and turn on Motion & Fitness.") {89                    Button("Open Settings") { if let url = URL(string: UIApplication.openSettingsURLString) { openURL(url) } }90                        .buttonStyle(SecondaryButtonStyle()).accessibilityIdentifier("steps.openSettings")91                    alternativeButton92                }93            case .restricted:94                notice(symbol: "lock.fill", tint: Theme.gold, title: "Motion access is restricted",95                       text: "Step counting is blocked on this iPhone by Screen Time or a device profile.") { alternativeButton }96            case .unsupported:97                notice(symbol: "figure.walk.circle", tint: Theme.gold, title: "Step counting is not available",98                       text: "This device has no pedometer, so steps cannot be counted here.") { alternativeButton }99            case .failed:100                notice(symbol: "exclamationmark.triangle.fill", tint: Theme.gold, title: "Step counting stopped",101                       text: "The pedometer reported an error. You can try again or use another mission.") {102                    Button("Try again") { startCounting() }.buttonStyle(SecondaryButtonStyle()).accessibilityIdentifier("steps.retry")103                    alternativeButton104                }105            }106        }107        .onAppear(perform: begin)108        .onDisappear { counter.stop() }109        .task(id: simulated) {110            // DEBUG simulation: about two steps per second through the same progress logic.111            guard simulated else { return }112            var total = 0113            while !Task.isCancelled, !challenge.isComplete {114                try? await Task.sleep(for: .milliseconds(500))115                total += 1116                ingest(total)117            }118        }119    }120121    private var alternativeButton: some View {122        Button("Use an alternative mission") { finish(.unavailable) }123            .buttonStyle(PrimaryButtonStyle()).accessibilityIdentifier("steps.useAlternative")124    }125126    // MARK: Counting127128    private var counting: some View {129        VStack(spacing: 22) {130            Spacer(minLength: 0)131            ZStack {132                Circle().stroke(Theme.surfaceRaised, lineWidth: 22)133                Circle().trim(from: 0, to: max(challenge.progress, 0.001))134                    .stroke(Theme.sunriseGradient, style: StrokeStyle(lineWidth: 22, lineCap: .round))135                    .rotationEffect(.degrees(-90))136                    .shadow(color: Theme.sunrise.opacity(0.55), radius: 14)137                    .animation(reduceMotion ? nil : .spring(duration: 0.6), value: challenge.steps)138                VStack(spacing: 2) {139                    Image(systemName: phase == .done ? "checkmark.circle.fill" : "figure.walk")140                        .font(.system(size: 30)).foregroundStyle(phase == .done ? Theme.success : Theme.gold)141                        .accessibilityHidden(true)142                    Text("\(challenge.steps)").font(.clock(86, weight: .semibold))143                        .contentTransition(reduceMotion ? .identity : .numericText(value: Double(challenge.steps)))144                        .animation(reduceMotion ? nil : .snappy, value: challenge.steps)145                        .minimumScaleFactor(0.5).lineLimit(1)146                        .accessibilityIdentifier("steps.count")147                    Text("of \(challenge.goal) steps").font(.orixHeadline).foregroundStyle(Theme.textSecondary)148                }149                .padding(34)150            }151            .frame(maxWidth: 300).aspectRatio(1, contentMode: .fit)152            .padding(11)153            .accessibilityElement(children: .ignore)154            .accessibilityLabel("Steps")155            .accessibilityValue("\(challenge.steps) of \(challenge.goal)")156157            Group {158                if phase == .done {159                    Label("Goal reached", systemImage: "checkmark.seal.fill").foregroundStyle(Theme.success)160                } else if challenge.steps == 0 {161                    Label("Start walking", systemImage: "arrow.forward.circle.fill").foregroundStyle(Theme.textPrimary)162                } else {163                    Label("\(challenge.remaining) to go", systemImage: "shoeprints.fill").foregroundStyle(Theme.textPrimary)164                }165            }166            .font(.orixTitle).accessibilityIdentifier("steps.status")167168            Spacer(minLength: 0)169            VStack(spacing: 6) {170                if simulated {171                    Label("Simulated steps (debug)", systemImage: "ladybug.fill").font(.orixCaption).foregroundStyle(Theme.gold)172                        .accessibilityIdentifier("steps.simulated")173                }174                Label("Step detection is approximate and may lag a few seconds. Keep the iPhone in your hand or pocket while you walk.", systemImage: "info.circle")175                    .font(.orixCaption).foregroundStyle(Theme.textTertiary).fixedSize(horizontal: false, vertical: true)176            }177            .frame(maxWidth: .infinity, alignment: .leading)178            .glassCard(padding: 14)179        }180    }181182    private func notice<Actions: View>(symbol: String, tint: Color, title: LocalizedStringKey, text: LocalizedStringKey, @ViewBuilder actions: () -> Actions) -> some View {183        VStack(spacing: 14) {184            Image(systemName: symbol).font(.system(size: 48)).foregroundStyle(tint).accessibilityHidden(true)185            Text(title).font(.orixTitle).multilineTextAlignment(.center)186            Text(text).font(.orixBody).foregroundStyle(Theme.textSecondary).multilineTextAlignment(.center).fixedSize(horizontal: false, vertical: true)187            actions()188        }189        .frame(maxWidth: .infinity).glassCard(padding: 22)190        .accessibilityElement(children: .contain)191        .accessibilityIdentifier("steps.notice")192    }193194    // MARK: Logic195196    private func begin() {197        started = Date()198        if Self.fakeSteps { beginSession(); simulated = true; return }199        // A refusal is reported first: it is the one case the user can fix in Settings.200        let authorization = StepCounter.authorization201        if authorization == .denied { phase = .denied; return }202        if authorization == .restricted { phase = .restricted; return }203        guard StepCounter.isAvailable else { phase = .unsupported; return }204        if authorization == .authorized { startCounting() } else { phase = .explain }205    }206207    private func beginSession() {208        challenge = StepChallenge(goal: mission.step.stepGoal, baseline: 0, startTime: 0)209        started = Date()210        phase = .counting211    }212213    private func startCounting() {214        guard StepCounter.isAvailable else { phase = .unsupported; return }215        counter.stop()216        beginSession()217        counter.start(from: started) { result in218            Task { @MainActor in219                switch result {220                case .success(let total): ingest(total)221                case .failure(let failure): if phase == .counting { phase = failure == .notAuthorized ? .denied : .failed }222                }223            }224        }225    }226227    private func ingest(_ cumulative: Int) {228        guard phase == .counting else { return }229        let before = challenge.steps230        challenge.ingest(cumulative: cumulative, at: Date().timeIntervalSince(started))231        guard challenge.steps != before else { return }232        if challenge.isComplete {233            phase = .done234            counter.stop()235            Haptics.play(.success); SoundFX.play(.correct)236            Task {237                try? await Task.sleep(for: .milliseconds(900))238                finish(.completed)239            }240        } else if challenge.steps / 10 != before / 10 {241            Haptics.play(.tick)242        }243    }244245    private func finish(_ result: MissionOutcome.Result) {246        guard !finished else { return }247        finished = true248        counter.stop()249        onFinish(MissionOutcome(result: result, mistakes: 0, duration: Date().timeIntervalSince(started), rounds: result == .completed ? 1 : 0))250    }251}252
Files main
Menu

Theme