import ActivityKit import Foundation @MainActor final class LiveActivityManager { static let shared = LiveActivityManager() private init() {} private var currentActivity: Activity? /// Call this when a ClimbSession starts to begin a Live Activity func startLiveActivity(for session: ClimbSession, gymName: String) async { await endLiveActivity() let attributes = SessionActivityAttributes( gymName: gymName, startTime: session.startTime ?? session.date) let initialContentState = SessionActivityAttributes.ContentState( elapsed: 0, totalAttempts: 0, completedProblems: 0 ) do { currentActivity = try Activity.request( attributes: attributes, content: .init(state: initialContentState, staleDate: nil), pushType: nil ) } catch { print("Failed to start live activity: \(error)") } } /// Call this to update the Live Activity with new session progress func updateLiveActivity(elapsed: TimeInterval, totalAttempts: Int, completedProblems: Int) async { guard let currentActivity else { return } let updatedContentState = SessionActivityAttributes.ContentState( elapsed: elapsed, totalAttempts: totalAttempts, completedProblems: completedProblems ) await currentActivity.update(.init(state: updatedContentState, staleDate: nil)) } /// Call this when a ClimbSession ends to end the Live Activity func endLiveActivity() async { guard let currentActivity else { return } await currentActivity.end(nil, dismissalPolicy: .immediate) self.currentActivity = nil } }