Files
coach-ios/ios/App/CoachLiveActivity/CoachLiveActivityWidget.swift
Sylvain Bettinelli 4f8699fd37 Vitesse en km/h sur la montre et dans la Live Activity
Suite de la demande : voir des km/h en courant, ce que l'app Exercice
d'Apple ne permet pas (vitesse réservée au vélo, allure min/km imposée en
course, aucun réglage).

La vitesse instantanée vient de HealthKit lui-même : HKLiveWorkoutDataSource
collecte .runningSpeed d'office en course extérieure (Series 6+) et
.cyclingSpeed à vélo (watchOS 11+). Elle est lue en mostRecentQuantity —
c'est la vitesse à l'instant t qu'on veut afficher, pas la moyenne de la
séance. Sur un appareil qui ne la produit pas, repli sur distance/temps.

Affichée sur les trois surfaces : écran de séance de la montre, Live
Activity (bannière + île dépliée) et vue native /live.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 13:31:13 +00:00

207 lines
9.2 KiB
Swift

// CoachLiveActivityWidget.swift
// Définition Widget pour la Live Activity (Lock Screen + Dynamic Island).
// Structure validée sur le template Apple Xcode 26.5 (Widget Extension /
// LiveActivity.swift) + SDK swiftinterface WidgetKit iOS 26.5
// (DynamicIsland init signature : expanded:compactLeading:compactTrailing:minimal:).
import ActivityKit
import WidgetKit
import SwiftUI
struct CoachLiveActivityWidget: Widget {
var body: some WidgetConfiguration {
ActivityConfiguration(for: CoachLiveActivityAttributes.self) { context in
// Lock screen / banner
lockScreenView(context: context)
.activityBackgroundTint(Color.black.opacity(0.55))
.activitySystemActionForegroundColor(.white)
// Tap sur la bannière Lock Screen -> ouvre /live dans l'app
// (qui présente CoachLiveView natif via openNativeLive).
.widgetURL(URL(string: "https://coach.hypnotruck.ch/live"))
} dynamicIsland: { context in
DynamicIsland {
// Expanded UI (long-press l'île)
DynamicIslandExpandedRegion(.leading) {
metricExpanded(label: "FC",
value: hrText(context.state),
color: .red,
symbol: "heart.fill")
}
DynamicIslandExpandedRegion(.trailing) {
metricExpanded(label: "Kcal",
value: kcalText(context.state),
color: .green,
symbol: "flame.fill")
}
DynamicIslandExpandedRegion(.center) {
Label(context.attributes.activityLabel,
systemImage: context.attributes.activitySymbol)
.font(.caption2.weight(.semibold))
.foregroundStyle(.secondary)
}
DynamicIslandExpandedRegion(.bottom) {
VStack(spacing: 10) {
HStack(spacing: 18) {
metricInline(label: "Distance",
value: distKmText(context.state),
unit: "km",
color: .orange)
Divider().frame(height: 28)
metricInline(label: "Vitesse",
value: speedText(context.state),
unit: "km/h",
color: .cyan)
Divider().frame(height: 28)
metricInline(label: "Durée",
value: elapsedText(context.state.elapsedSec),
unit: "",
color: .white)
}
.frame(maxWidth: .infinity)
controls(state: context.state)
}
}
} compactLeading: {
HStack(spacing: 3) {
Image(systemName: "heart.fill")
.foregroundStyle(.red)
Text(hrText(context.state))
.font(.caption2.weight(.bold).monospacedDigit())
}
} compactTrailing: {
Text(elapsedText(context.state.elapsedSec))
.font(.caption2.weight(.semibold).monospacedDigit())
.foregroundStyle(.white)
} minimal: {
Image(systemName: "heart.fill")
.foregroundStyle(.red)
.symbolEffect(.pulse, isActive: context.state.isLive)
}
// Tap sur l'île (compact ou minimal) -> ouvre /live dans l'app.
// Pour la vue expanded, c'est le système qui gère le tap = ouvre l'app.
.widgetURL(URL(string: "https://coach.hypnotruck.ch/live"))
.keylineTint(.red)
}
}
// MARK: - Lock screen layout
@ViewBuilder
private func lockScreenView(context: ActivityViewContext<CoachLiveActivityAttributes>) -> some View {
VStack(spacing: 12) {
HStack(spacing: 8) {
Image(systemName: context.attributes.activitySymbol)
.foregroundStyle(.white)
Text(context.attributes.activityLabel)
.font(.headline)
Spacer()
Image(systemName: "heart.fill")
.foregroundStyle(.red)
.symbolEffect(.pulse, isActive: context.state.isLive)
Text(context.state.isLive ? "En direct" : "Connexion perdue")
.font(.caption.weight(.semibold))
.foregroundStyle(context.state.isLive ? .green : .orange)
}
HStack(spacing: 14) {
metricBlock(value: hrText(context.state), unit: "bpm", color: .red)
metricBlock(value: kcalText(context.state), unit: "kcal", color: .green)
metricBlock(value: distKmText(context.state), unit: "km", color: .orange)
metricBlock(value: speedText(context.state), unit: "km/h", color: .cyan)
metricBlock(value: elapsedText(context.state.elapsedSec), unit: "", color: .white)
}
controls(state: context.state)
}
.padding(.horizontal, 14)
.padding(.vertical, 12)
}
// MARK: - Contrôles (iOS 17+)
/// Pause/Reprendre et Terminer, comme l'app Exercice.
/// Sur iOS 16, ActivityKit n'accepte aucun bouton : la Live Activity reste
/// purement informative, sans rien casser.
@ViewBuilder
private func controls(state: CoachLiveActivityAttributes.ContentState) -> some View {
if #available(iOS 17.0, *) {
HStack(spacing: 10) {
Button(intent: CoachTogglePauseIntent(resuming: state.isPaused)) {
Label(state.isPaused ? "Reprendre" : "Pause",
systemImage: state.isPaused ? "play.fill" : "pause.fill")
.font(.caption.weight(.semibold))
.frame(maxWidth: .infinity)
}
.tint(state.isPaused ? .green : .yellow)
Button(intent: CoachEndWorkoutIntent()) {
Label("Terminer", systemImage: "stop.fill")
.font(.caption.weight(.semibold))
.frame(maxWidth: .infinity)
}
.tint(.red)
}
.buttonStyle(.borderedProminent)
.controlSize(.small)
}
}
@ViewBuilder
private func metricBlock(value: String, unit: String, color: Color) -> some View {
VStack(spacing: 0) {
Text(value)
.font(.system(.title3, design: .rounded).weight(.heavy).monospacedDigit())
.foregroundStyle(color)
if !unit.isEmpty {
Text(unit).font(.caption2).foregroundStyle(.secondary)
}
}
.frame(maxWidth: .infinity)
}
@ViewBuilder
private func metricExpanded(label: String, value: String, color: Color, symbol: String) -> some View {
VStack(alignment: .leading, spacing: 2) {
Label(label, systemImage: symbol)
.font(.caption2.weight(.semibold))
.foregroundStyle(color)
Text(value)
.font(.title2.weight(.heavy).monospacedDigit())
.foregroundStyle(color)
}
}
@ViewBuilder
private func metricInline(label: String, value: String, unit: String, color: Color) -> some View {
HStack(spacing: 4) {
Text(label).font(.caption2).foregroundStyle(.secondary)
Text(value).font(.callout.weight(.bold).monospacedDigit()).foregroundStyle(color)
if !unit.isEmpty {
Text(unit).font(.caption2).foregroundStyle(.tertiary)
}
}
}
// MARK: - Formatters (dupliqués ici car non-import de LiveStore depuis l'extension)
private func hrText(_ s: CoachLiveActivityAttributes.ContentState) -> String {
s.heartRate > 0 ? "\(Int(s.heartRate.rounded()))" : ""
}
private func kcalText(_ s: CoachLiveActivityAttributes.ContentState) -> String {
s.activeEnergyKcal > 0 ? "\(Int(s.activeEnergyKcal.rounded()))" : ""
}
private func distKmText(_ s: CoachLiveActivityAttributes.ContentState) -> String {
s.distanceMeters > 0 ? String(format: "%.2f", s.distanceMeters / 1000) : ""
}
private func speedText(_ s: CoachLiveActivityAttributes.ContentState) -> String {
s.speedKmh > 0 ? String(format: "%.1f", s.speedKmh) : ""
}
private func elapsedText(_ sec: TimeInterval) -> String {
let total = Int(sec)
let h = total / 3600
let m = (total % 3600) / 60
let s = total % 60
if h > 0 { return "\(h):\(String(format: "%02d", m)):\(String(format: "%02d", s))" }
return "\(m):\(String(format: "%02d", s))"
}
}