mycode/myApp/Keging/IOS/WorkoutView.swift
songyc macbook b751247ba7 feat(keging): 아이폰 시작 세트의 워치 심박 측정 — startWatchApp + 미러링 세션, 배지·사전 경고 폐지 (9차)
- 의도(사용자 TestFlight 피드백): 폰으로 운동해도 워치를 차고 있으면 워치가 심박을 재고,
  진동은 시작한 기기에서만. 종전 '워치 연동됨' 배지는 워치 앱 포그라운드 여부(isReachable)만
  보여 주던 것이라 폐지
- iOS: WatchHeartRateBridge — 시작 시 HKHealthStore.startWatchApp(폰 설정 운동 유형)으로 워치 앱을
  깨우고, 워치가 미러링한 HKWorkoutSession을 workoutSessionMirroringStartHandler로 받아 심박 수신,
  완주/중단 명령 전송(finish/discard). 워치를 못 열거나 30초 안에 미러링이 안 붙으면 폰 단독
  (+설정에 따라 '워치 앱을 열지 못했어요' 알럿, app.watchWarn 재사용) 및 WatchConnectivity로
  워치 세션 폐기 명령. 워치 저장 결과(saved/failed)는 WC로 회신받고 15초 내 미회신이면 폰 사후 저장 폴백.
  워치 깨우기는 폰 건강 권한 응답 뒤에(첫 실행 경합 방지). 건강 읽기 권한(심박·활성 에너지) 추가
  — 워치 세션 센서 수집용(권한 공유)
- 워치: WatchAppDelegate.handle(workoutConfiguration) → MirroredWorkoutSession(라이브 빌더, 무진동·무타이머,
  심박을 미러링 채널로 전송, finish 시 저장+강도 relate 후 WC로 결과 통보, discard/끊김 시 폐기,
  미러링 30초 타임아웃, 앱 재기동 시 잔류 세션 복구·폐기). 화면 '아이폰에서 진행 중 ♥bpm'(중단 버튼).
  WatchHealthAuth로 권한 공용화
- UI: 첫 화면 배지·확인 창 제거, 운동 화면 횟수 아래 워치 상태 줄(연결 중/♥bpm/아이폰만),
  설정 토글 '워치 연결 실패 경고', 도움말 3건 갱신. l10n 카탈로그 3종 missing/stale 0
- DEBUG: -testConfig(35초 세트), -mockWatchHeartRate <bpm>(상태 줄 QA·스크린샷). watchHR 카테고리 notice 로그
- 시뮬 검증(페어링 심): startWatchApp → 워치 기동·권한·세션·가짜 심박·'아이폰에서 진행 중'까지 동작,
  워치 startMirroring 성공 반환 — 그러나 폰 미러링 핸들러는 시뮬에서 불리지 않음(애플 샘플도 실기기 전용)
  → 30초 타임아웃·알럿·WC 폐기·폰 폴백 저장 경로 확인, 워치 자체 세트 정상. 3타깃 빌드 그린·경고 0.
  미러링 수신·완주 저장·회신은 실기기 TestFlight 재테스트 필요
- 문서·마케팅: CLAUDE.md §3.8 신설·§1/§3.7/§4/§6/§7 갱신, 설명 3언어·whats-new·review-notes·PRIVACY.md
  (아이폰 읽기 권한 설명 — GitHub 게시본 갱신 필요), 스크린샷 01·08(배지 제거)·02·03(♥78 상태 줄) 재촬영·합성

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UPmp29DQHY6Ahfss5SRopT
2026-09-05 10:13:48 +09:00

266 lines
10 KiB
Swift

//
// WorkoutView.swift
// Keging
//
// . .
// ( //) , (§3.8).
//
import SwiftUI
struct WorkoutView: View {
@EnvironmentObject private var engine: KegelEngine
@ObservedObject private var bridge = WatchHeartRateBridge.shared
/// ( > )
@AppStorage("app.watchWarn", store: AppGroup.defaults) private var warnNoWatch = true
@State private var confirmStop = false
var body: some View {
ZStack {
AppTheme.background.ignoresSafeArea()
switch engine.state {
case let .running(phase, rep, phaseStart, phaseEnd):
runningView(phase: phase, rep: rep, phaseStart: phaseStart, phaseEnd: phaseEnd)
case let .finished(reps):
finishedView(reps: reps)
case .idle:
Color.clear
}
}
.alert("워치 앱을 열지 못했어요", isPresented: launchAlertPresented) {
Button("확인") {}
} message: {
Text("심박 없이 아이폰만으로 기록해요. 워치를 차고 있는지, 케깅 워치 앱이 설치돼 있는지, 워치의 건강 권한이 허용돼 있는지 확인해 주세요.")
}
.onAppear {
#if DEBUG
if CommandLine.arguments.contains("-confirmStop") { confirmStop = true }
#endif
}
}
private var launchAlertPresented: Binding<Bool> {
Binding(
get: { bridge.launchFailed && warnNoWatch },
set: { presented in if !presented { bridge.launchFailed = false } }
)
}
/// / bpm / ( · )
@ViewBuilder
private var watchStatus: some View {
switch bridge.state {
case .launching:
statusLine(symbol: "applewatch", label: Text("워치 연결 중"))
case .measuring:
if let bpm = bridge.heartRate {
HStack(spacing: 5) {
Image(systemName: "heart.fill")
.foregroundStyle(.red)
Text(verbatim: "\(Int(bpm.rounded()))")
.monospacedDigit()
.foregroundStyle(.primary)
Text("워치 심박")
.foregroundStyle(.secondary)
}
.font(.footnote.weight(.medium))
.accessibilityElement(children: .combine)
} else {
statusLine(symbol: "applewatch", label: Text("워치 심박 준비 중"))
}
case .unavailable:
statusLine(symbol: "iphone", label: Text("아이폰만으로 기록"))
case .idle, .finishing:
EmptyView()
}
}
private func statusLine(symbol: String, label: Text) -> some View {
HStack(spacing: 5) {
Image(systemName: symbol)
label
}
.font(.footnote.weight(.medium))
.foregroundStyle(.secondary)
.accessibilityElement(children: .combine)
}
private func runningView(phase: KegelPhase, rep: Int, phaseStart: Date, phaseEnd: Date) -> some View {
let phaseColor = Self.color(for: phase)
let progress = phase == .prepare
? 0
: (Double(rep - 1) + (phase == .relax ? 0.5 : 0)) / Double(max(1, engine.config.reps))
return VStack(spacing: 0) {
HStack(alignment: .firstTextBaseline, spacing: 5) {
Text(verbatim: "\(rep)")
.font(.system(size: 46, weight: .bold))
.monospacedDigit()
.foregroundStyle(phaseColor)
.contentTransition(.numericText())
.animation(.snappy, value: rep)
Text(verbatim: "/ \(engine.config.reps)")
.font(.title3.weight(.semibold))
.monospacedDigit()
.foregroundStyle(.secondary)
}
.padding(.top, 16)
.accessibilityElement(children: .ignore)
.accessibilityLabel(Text("현재 \(rep)번째, 전체 \(engine.config.reps)"))
watchStatus
.padding(.top, 6)
Spacer()
ZStack {
//
Circle()
.stroke(AppTheme.surface, lineWidth: 10)
.frame(width: 344, height: 344)
Circle()
.trim(from: 0, to: progress)
.stroke(phaseColor.opacity(0.85), style: StrokeStyle(lineWidth: 10, lineCap: .round))
.rotationEffect(.degrees(-90))
.frame(width: 344, height: 344)
.animation(.easeInOut(duration: 0.5), value: progress)
PhaseCircle(phase: phase, phaseStart: phaseStart, phaseEnd: phaseEnd)
VStack(spacing: 6) {
Text(phase.label)
.font(.system(size: 44, weight: .bold))
Text(timerInterval: phaseStart...phaseEnd, countsDown: true)
.font(.title2.weight(.medium))
.monospacedDigit()
.opacity(0.85)
}
.foregroundStyle(Self.textColor(for: phase))
}
Spacer()
// ( )
Group {
if confirmStop {
VStack(spacing: 12) {
Text("중단하면 이 세트는 기록되지 않아요.")
.font(.footnote)
.foregroundStyle(.secondary)
HStack(spacing: 12) {
Button {
withAnimation(.snappy) { confirmStop = false }
} label: {
Text("계속하기")
.font(.headline)
.frame(maxWidth: .infinity)
}
.buttonStyle(.borderedProminent)
Button(role: .destructive) {
engine.stop()
} label: {
Text("중단하기")
.font(.headline)
.frame(maxWidth: .infinity)
}
.buttonStyle(.bordered)
.tint(.red)
}
}
.padding(.horizontal, 24)
.transition(.scale(scale: 0.9).combined(with: .opacity))
} else {
Button {
withAnimation(.snappy) { confirmStop = true }
} label: {
Text("중단")
.font(.headline)
.frame(maxWidth: 160)
}
.buttonStyle(.bordered)
.tint(.red)
.transition(.scale(scale: 0.9).combined(with: .opacity))
}
}
.padding(.bottom, 30)
}
}
/// = , =, =
static func color(for phase: KegelPhase) -> Color {
switch phase {
case .prepare: Color(light: Color(hex: "#7C8A81"), dark: Color(hex: "#5E6B64"))
case .contract: AppTheme.green
case .relax: AppTheme.yellow
}
}
static func textColor(for phase: KegelPhase) -> Color {
switch phase {
case .prepare: Color(light: .white, dark: Color(hex: "#10140F"))
case .contract: Color(light: .white, dark: Color(hex: "#0F2018"))
case .relax: Color(hex: "#33260A")
}
}
private func finishedView(reps: Int) -> some View {
VStack(spacing: 18) {
Image(systemName: "checkmark.circle.fill")
.font(.system(size: 84))
.foregroundStyle(AppTheme.green)
Text("완료!")
.font(.largeTitle.bold())
Text("\(reps)회를 모두 마쳤어요.")
.font(.body)
.foregroundStyle(.secondary)
Button {
engine.acknowledgeFinish()
} label: {
Text("확인")
.font(.headline)
.frame(maxWidth: 160)
}
.buttonStyle(.borderedProminent)
.padding(.top, 12)
}
}
}
/// ( · )
private struct PhaseCircle: View {
let phase: KegelPhase
let phaseStart: Date
let phaseEnd: Date
@State private var scale: CGFloat = 1
private var color: Color { WorkoutView.color(for: phase) }
var body: some View {
Circle()
.fill(
LinearGradient(
colors: [color, color.opacity(0.8)],
startPoint: .top, endPoint: .bottom
)
)
.frame(width: 300, height: 300)
.scaleEffect(scale)
.shadow(color: color.opacity(0.3), radius: 26, x: 0, y: 10)
.animation(.easeInOut(duration: 0.4), value: phase)
.onAppear { animate() }
.onChange(of: phase) { animate() }
}
private func animate() {
let duration = max(0.3, phaseEnd.timeIntervalSince(phaseStart))
// : ( )
let (from, to): (CGFloat, CGFloat) = switch phase {
case .prepare: (0.62, 1.0)
case .contract: (1.0, 0.62)
case .relax: (0.62, 1.0)
}
var transaction = Transaction()
transaction.disablesAnimations = true
withTransaction(transaction) { scale = from }
withAnimation(.easeInOut(duration: duration)) { scale = to }
}
}