Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 42 additions & 14 deletions Projects/App/Sources/Application/SceneDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate {
private var appGate: AppGate?
/// 위젯에서 온 프리셋 시작의 알람 권한 게이트 구독 보관함 (NM-360).
private var permissionBag = Set<AnyCancellable>()
private var alarmBag = Set<AnyCancellable>()

/*
┌─────────────────────────────────┬───────────────────────────────────────┐
Expand Down Expand Up @@ -79,6 +80,13 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate {

appGate = AppGate(windowScene: windowScene)

// 앱이 떠 있는 동안 앱 밖(잠금화면 · Dynamic Island · 워치)에서 알람을 끄면 바로 반영한다 —
// 예전엔 만료 카드가 남아 [완료]를 한 번 더 눌러야 사라졌다 (NM-635).
DIContainer.shared.resolve(TimerAlarmScheduling.self).alarmsChanged
.receive(on: DispatchQueue.main)
.sink { [weak self] in self?.syncTimersWhileActive() }
.store(in: &alarmBag)

// 콜드런치 딥링크는 저장만 — 탭바가 뜬 뒤(onTabBarReady) 처리한다.
// 미로그인 상태면 로그인·동의를 마치고 탭바가 뜰 때 실행된다 (NM-410).
//
Expand Down Expand Up @@ -318,6 +326,7 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate {
// App Intent(AlarmKit)가 App Group 저장소를 직접 바꿨을 수 있음 — 먼저 재동기화.
useCase.reload() // 1. 디스크 → 메모리 다시 읽기
useCase.refresh() // 2. 현재 시각 기준으로 상태 재계산
useCase.syncWithSystemAlarms() // 2-1. 앱 밖에서 끈 알람의 타이머 정리 (NM-635)
// 3. 알람 권한 캐시 갱신(NM-360) — 위젯 무음-시작 라우팅과 워치 시작 게이트가 읽는
// alarmAuthorized 플래그를 실제 권한으로 최신화하고 워치에 즉시 재동기화한다.
// 이게 없으면 플래그가 미기록(nil)으로 남아 워치가 권한 없이도 시작을 허용한다.
Expand All @@ -326,6 +335,39 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate {
// 스토어 리뷰 요청 조건 — 첫 실행 시각 · 앱을 연 날 (NM-560).
StoreReview.shared.recordAppActive()

drainOutsideTimerEvents()
if appCoordinator?.isTabBarShown == true {
StoreReview.shared.requestPendingTimerMomentIfNeeded(in: scene as? UIWindowScene)
}

// Remote Config 최신값 fetch 후 강제 업데이트/점검 게이트 갱신(포그라운드 복귀 포함).
//
// fetch 만으로는 부족하다 — 릴리즈는 캐시가 12시간이라 그 안에는 서버로 가지 않는다.
// 점검 모드를 켜야 하는 순간의 사용자들은 전부 캐시를 갖고 있어 옛 값을 본다.
// 그래서 **사용 중 실시간 청취**를 함께 켠다(Firebase 권장 구조).
Task { @MainActor in
await RemoteConfigService.shared.fetchAndActivate()
appGate?.evaluate()
RemoteConfigService.shared.startListening()
}
}

/// 앱이 앞에 있을 때 시스템 알람이 바뀌었다 — 앱 밖에서 끈 알람의 타이머를 지우고, 리뷰 요청도 지금 본다.
/// 뒤에 있을 때는 다음 활성화(sceneDidBecomeActive)가 같은 일을 한다.
private func syncTimersWhileActive() {
guard let scene = window?.windowScene, scene.activationState == .foregroundActive else { return }
let useCase = DIContainer.shared.resolve(TimerUseCase.self)
useCase.reload()
useCase.refresh()
useCase.syncWithSystemAlarms()
drainOutsideTimerEvents()
if appCoordinator?.isTabBarShown == true {
StoreReview.shared.requestPendingTimerMomentIfNeeded(in: scene)
}
}

/// 앱 밖(위젯 · 알람 완료 인텐트)에서 쌓아 둔 타이머 이벤트를 꺼내 보낸다.
private func drainOutsideTimerEvents() {
// 위젯이 앱 밖(백그라운드 AppIntent, iOS 26.1+ 승인)에서 시작한 타이머 지연 집계.
// 위젯 프로세스는 Firebase 를 링크하지 않아 timer_start 를 직접 못 보낸다(§위젯 지연로깅).
let widgetStarts = WidgetAnalyticsQueue.drainTimerStarts()
Expand Down Expand Up @@ -353,20 +395,6 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate {
if !outsideCompletes.isEmpty {
StoreReview.shared.recordTimerCompletedOutsideApp(at: outsideCompletes.map(\.completedAt))
}
if appCoordinator?.isTabBarShown == true {
StoreReview.shared.requestPendingTimerMomentIfNeeded(in: scene as? UIWindowScene)
}

// Remote Config 최신값 fetch 후 강제 업데이트/점검 게이트 갱신(포그라운드 복귀 포함).
//
// fetch 만으로는 부족하다 — 릴리즈는 캐시가 12시간이라 그 안에는 서버로 가지 않는다.
// 점검 모드를 켜야 하는 순간의 사용자들은 전부 캐시를 갖고 있어 옛 값을 본다.
// 그래서 **사용 중 실시간 청취**를 함께 켠다(Firebase 권장 구조).
Task { @MainActor in
await RemoteConfigService.shared.fetchAndActivate()
appGate?.evaluate()
RemoteConfigService.shared.startListening()
}
}

/*
Expand Down
2 changes: 2 additions & 0 deletions Projects/App/Sources/DI/RegisterDependencies.swift
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,8 @@ enum RegisterDependencies {
category: info.category.displayName,
durationSec: info.durationSec
))
// 앱 밖에서 끈 알람을 앱이 정리했다 — 리뷰 요청은 앱 밖 완료로 본다(NM-635 · NM-560).
if info.endedOutsideApp { StoreReview.shared.recordTimerCompletedOutsideApp() }
case .cancelled:
AppAnalytics.track(.timerCancel(
category: info.category.displayName,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,16 @@ public protocol TimerAlarmScheduling {
func resumeAlarm(id: UUID, label: String, categoryName: String, body: String, fireDate: Date)
/// 남은 시간을 바꿔 정지 상태로 다시 예약 — 정지된 알람의 남은 시간은 바꿀 수 없어서(정지 중 연장).
func reschedulePausedAlarm(id: UUID, label: String, categoryName: String, body: String, remaining: Int)
/// 시스템에 살아 있는 알람 id — 앱 밖(잠금화면 · Dynamic Island · 워치)에서 끈 알람은 여기서 빠진다.
/// nil = 알 수 없음. 그때는 타이머를 정리하지 않는다 (NM-635).
func liveAlarmIDs() -> Set<UUID>?
/// 시스템 알람 목록이 바뀔 때마다 — 앱 밖에서 끈 경우를 앱이 떠 있는 동안 바로 반영한다 (NM-635).
var alarmsChanged: AnyPublisher<Void, Never> { get }
}

public extension TimerAlarmScheduling {
func liveAlarmIDs() -> Set<UUID>? { nil }
var alarmsChanged: AnyPublisher<Void, Never> { Empty().eraseToAnyPublisher() }
}

public enum TimerAlarmAuthorizationStatus: Equatable, Sendable {
Expand Down
37 changes: 37 additions & 0 deletions Projects/Domain/Sources/UseCase/TimerUseCase.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ public struct TimerEndInfo: Sendable {
public let durationSec: Int
public let elapsedSec: Int
public let remainingSec: Int
/// 앱 밖(잠금화면 · Dynamic Island · 워치 알람)에서 끈 알람을 앱이 뒤늦게 정리했다 (NM-635).
public var endedOutsideApp = false
}

public protocol TimerUseCase {
Expand All @@ -37,6 +39,8 @@ public protocol TimerUseCase {
func refresh()
/// 외부 프로세스(App Intent 등)가 App Group 저장소를 직접 바꾼 뒤 재동기화
func reload()
/// 시스템 알람과 맞춘다 — 만료됐는데 알람이 없으면 앱 밖에서 끈 것이라 지운다 (NM-635)
func syncWithSystemAlarms()
/// 워치에서 온 명령 실행 — 알람 예약은 폰 단독이라 워치는 명령만 보낸다(NM-269)
func handleWatchCommand(_ command: TimerWatchCommand)

Expand Down Expand Up @@ -208,6 +212,39 @@ public final class DefaultTimerUseCase: TimerUseCase {
timers.send(repository.loadTimers())
}

/*
시스템 알람(AlarmKit)이 만료 카드의 기준이다 (NM-635).

알람을 앱 밖(잠금화면 · Dynamic Island · 워치)에서 끄면 시스템에서 사라진다. 완료 인텐트가
저장소를 지우지만, 인텐트가 실행되지 않는 경로가 있으면(위젯이 예약한 알람 — 인텐트가 앱에 없었다)
타이머가 남아 앱에서 [완료]를 한 번 더 눌러야 사라졌다.

그래서 만료 시각이 지났는데 알람이 없는 타이머는 앱 밖에서 끝낸 것으로 보고 지운다.
울리기 전(카운트다운) · 일시정지 타이머는 알람이 살아 있어야 정상이라 건드리지 않는다 —
없다면 다른 문제이고, 이 규칙으로 덮을 일이 아니다.
*/
public func syncWithSystemAlarms() {
guard let live = alarmScheduler.liveAlarmIDs() else { return }
let stopped = timers.value.filter { timer in
let expired = timer.state == .ringing || (timer.state == .running && timer.remainingSeconds() == 0)
return expired && !live.contains(timer.id)
}
guard !stopped.isEmpty else { return }
for t in stopped {
var info = TimerEndInfo(
reason: .completed,
category: t.category,
durationSec: t.duration,
elapsedSec: t.duration,
remainingSec: 0
)
info.endedOutsideApp = true
timerEnded.send(info)
}
let ids = Set(stopped.map(\.id))
mutate { $0.removeAll { ids.contains($0.id) } }
}

public func handleWatchCommand(_ command: TimerWatchCommand) {
switch command {
case .start(let presetId):
Expand Down
100 changes: 100 additions & 0 deletions Projects/Domain/Tests/Sources/TimerSystemAlarmSyncTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import XCTest
import Combine
@testable import Domain

// 시스템 알람(AlarmKit)이 만료 카드의 기준이다 (NM-635) —
// 앱 밖에서 끈 알람은 시스템에서 사라지므로, 만료됐는데 알람이 없는 타이머는 앱이 지운다.
final class TimerSystemAlarmSyncTests: XCTestCase {

private var scheduler: FakeAlarmScheduler!
private var cancellables = Set<AnyCancellable>()

override func setUp() {
super.setUp()
scheduler = FakeAlarmScheduler()
cancellables = []
}

private func makeUseCase(_ timers: [TreatmentTimerModel]) -> (DefaultTimerUseCase, TimersRepository) {
let repository = TimersRepository(timers: timers)
return (DefaultTimerUseCase(repository: repository, alarmScheduler: scheduler), repository)
}

private func timer(_ label: String, endsIn seconds: TimeInterval, state: TreatmentTimerState = .running) -> TreatmentTimerModel {
TreatmentTimerModel(label: label, category: .examination, duration: 5, endAt: Date().addingTimeInterval(seconds), state: state)
}

func test_만료됐는데_알람이_없으면_앱_밖_완료로_지운다() {
let ringing = timer("울림", endsIn: -10, state: .ringing)
let expired = timer("만료", endsIn: -1)
let (useCase, repository) = makeUseCase([ringing, expired])
scheduler.live = []
var ended: [TimerEndInfo] = []
useCase.timerEnded.sink { ended.append($0) }.store(in: &cancellables)

useCase.syncWithSystemAlarms()

XCTAssertTrue(useCase.timers.value.isEmpty)
XCTAssertTrue(repository.timers.isEmpty)
XCTAssertEqual(ended.count, 2)
XCTAssertTrue(ended.allSatisfy { $0.reason == .completed && $0.endedOutsideApp })
}

func test_알람이_울리는_중이면_만료_카드를_남긴다() {
let ringing = timer("울림", endsIn: -10, state: .ringing)
let (useCase, _) = makeUseCase([ringing])
scheduler.live = [ringing.id]

useCase.syncWithSystemAlarms()

XCTAssertEqual(useCase.timers.value.map(\.id), [ringing.id])
}

func test_울리기_전이나_일시정지_타이머는_알람이_없어도_건드리지_않는다() {
let running = timer("진행", endsIn: 60)
var paused = timer("정지", endsIn: -10, state: .paused)
paused.remaining = 30
let (useCase, _) = makeUseCase([running, paused])
scheduler.live = []

useCase.syncWithSystemAlarms()

XCTAssertEqual(Set(useCase.timers.value.map(\.id)), [running.id, paused.id])
}

func test_알람_목록을_모르면_정리하지_않는다() {
let ringing = timer("울림", endsIn: -10, state: .ringing)
let (useCase, _) = makeUseCase([ringing])
scheduler.live = nil

useCase.syncWithSystemAlarms()

XCTAssertEqual(useCase.timers.value.count, 1)
}
}

private final class FakeAlarmScheduler: TimerAlarmScheduling {
var live: Set<UUID>?

func requestAuthorization() -> AnyPublisher<Bool, Never> { Just(true).eraseToAnyPublisher() }
func authorizationStatus() -> AnyPublisher<TimerAlarmAuthorizationStatus, Never> { Just(.authorized).eraseToAnyPublisher() }
func scheduleAlarm(id: UUID, label: String, categoryName: String, body: String, fireDate: Date) {}
func cancelAlarm(id: UUID) {}
func pauseAlarm(id: UUID) {}
func resumeAlarm(id: UUID, label: String, categoryName: String, body: String, fireDate: Date) {}
func reschedulePausedAlarm(id: UUID, label: String, categoryName: String, body: String, remaining: Int) {}
func liveAlarmIDs() -> Set<UUID>? { live }
}

private final class TimersRepository: TimerRepositoryProtocol {
var timers: [TreatmentTimerModel]

init(timers: [TreatmentTimerModel]) { self.timers = timers }

func loadTimers() -> [TreatmentTimerModel] { timers }
func saveTimers(_ timers: [TreatmentTimerModel]) { self.timers = timers }
func loadPresets() -> [TimerPresetModel] { [] }
func savePresets(_ presets: [TimerPresetModel]) {}
func setAlarmAuthorized(_ authorized: Bool) {}
func alarmAuthorizedFlag() -> Bool? { nil }
}
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ final class StubTimerUseCase: TimerUseCase {
func updateMemo(id: UUID, memo: String?) {}
func refresh() {}
func reload() {}
func syncWithSystemAlarms() {}
func handleWatchCommand(_ command: TimerWatchCommand) {}
func addPreset(label: String, category: TimerCategory, duration: Int) {}
func updatePreset(_ preset: TimerPresetModel) {}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,35 @@ import TimerShared

// iOS 26 AlarmKit 알람 스케줄러 — Clock 앱 동급 시스템 알람.
// 강제종료/잠금/무음/Focus 모두 뚫고 풀스크린+루핑으로 울림(AlarmManager가 시스템 수준 관리).
// [완료](stop)는 시스템 자동 처리 + TimerStopIntent가 모델 삭제.
// [완료](stop)는 시스템 자동 처리 + TimerStopIntent가 모델 삭제. 인텐트가 못 지운 타이머는
// 앱이 알람 목록과 맞춰 정리한다(liveAlarmIDs · alarmsChanged, NM-635).
// (AlarmPresentation.Alert 의 비권장 init이 iOS 26.1+ 이므로 26.1 게이트)
@available(iOS 26.1, *)
public final class AlarmKitAlarmScheduler: TimerAlarmScheduling {

public init() {}
private let alarmsChangedSubject = PassthroughSubject<Void, Never>()
private var updatesTask: Task<Void, Never>?

public init() {
// 앱 밖(잠금화면 · Dynamic Island · 워치)에서 끈 알람도 여기로 들어온다 (NM-635).
updatesTask = Task { [weak self] in
for await _ in AlarmManager.shared.alarmUpdates {
await MainActor.run { self?.alarmsChangedSubject.send() }
}
}
}

deinit { updatesTask?.cancel() }

public var alarmsChanged: AnyPublisher<Void, Never> {
alarmsChangedSubject.eraseToAnyPublisher()
}

/// 위젯이 예약한 알람도 앱의 알람이라 함께 나온다.
public func liveAlarmIDs() -> Set<UUID>? {
guard let alarms = try? AlarmManager.shared.alarms else { return nil }
return Set(alarms.map(\.id))
}

public func requestAuthorization() -> AnyPublisher<Bool, Never> {
Future { promise in
Expand Down