FocusAction/Services/TimerSyncManager.swift(iOS/watchOS 共通ファイル)が、iPhone と Apple Watch
間でタイマーの実行状態をリアルタイムに近い形で同期する。
対象は「今どのモードで、あと何秒残っていて、動いているか」といったタイマーの実行状態のみ。
FocusSessionの履歴データやTag(タグ)データはこの仕組みの対象外で、CloudKit 経由で別途 同期される。watchOS 側でタグを選ぶWatchTagListViewも、CloudKit 経由で端末に反映されたTagを@Queryで参照しているだけで、WatchConnectivity 経由の即時反映は行っていない (iPhoneでタグを作った直後は、Watch側に届くまでCloudKitの同期を待つ必要がある)。
watchOS 側の
TimerStoreは App(FocusAction_for_Watch_Watch_AppApp)が@Stateで1つだけ生成し、.environmentでWatchTagListView/WatchTimerViewに配る。TimerSyncManager.start(with:)も App のルートの.taskで呼ぶため、画面遷移をまたいでも受信先のインスタンスは変わらない。
struct TimerSyncState {
let timerModeRawValue: String // .focus / .shortBreak
let totalTime: TimeInterval
let timeRemaining: TimeInterval
let isTimerRunning: Bool
let sessionStartTimestamp: TimeInterval?
let referenceTimestamp: TimeInterval // このスナップショットを作った時刻
}referenceTimestamp が重要で、送信側と受信側の間にタイムラグがあっても、受信側で
「スナップショット作成時刻からの経過時間」を計算して残り時間を補正できるようにしている
(TimerState.apply(_:now:) 内の計算)。
TimerSyncManager.sendState(_:)(#if os(iOS) のみ)が、ペア設定済みかつ Watch アプリがインストール
済みの場合に WCSession.updateApplicationContext(_:) で TimerState を送信する。
呼び出し元は FocusAction/Services/TimerEventHandlers.swift の WatchSyncTimerEventHandler
(iOS の TimerStore にのみ注入)で、以下の TimerEvent を受けたときに送る:
.started/.paused(開始/一時停止).reset.modeSwitched(モード切替、タイマー完了時の自動切替を含む)
updateApplicationContext は最新の内容で上書きされる性質があるため、毎秒ではなく状態が
変化したタイミングでのみ呼び出せば十分、という設計判断がコメントに明記されている。
TimerSyncManager.start(with:)が watchOS の App の.taskで呼ばれ、applyLatestContextIfAvailable()で起動直後に直近のapplicationContextを即座に反映する。WCSessionDelegate.session(_:didReceiveApplicationContext:)(#if os(watchOS))で新しい状態を 受信するたびにTimerStore.applyRemoteState(_:)を呼ぶ。- セッションのアクティベーション完了時(
activationDidCompleteWith:)にも、watchOS 側では 直近のコンテキストを再適用する。
受信した TimerSyncState を Watch 側の TimerStore に反映するロジック。計算部分は
TimerState.apply(_:now:) にあり、FocusActionTests で単体テストしている。
- 実行中のタイマー購読を一旦停止。
timerMode/totalTime/sessionStartDateを同期。isTimerRunning == trueの場合、referenceDateからの経過時間を引いた残り時間を計算。 経過しきっていれば停止状態に、残っていれば終了時刻endDate(referenceDate + timeRemaining)を 設定してタイマー購読を再開する。isTimerRunning == falseの場合はそのままtimeRemainingを反映し、endDateをnilにする。
iPhone (TimerStore) Watch (TimerStore)
│ toggleTimer / resetTimer / switchMode
▼ TimerEvent
WatchSyncTimerEventHandler
▼
TimerSyncManager.sendState()
│ WCSession.updateApplicationContext(state.dictionary)
▼
── WatchConnectivity ──▶
WCSessionDelegate
.didReceiveApplicationContext
▼
TimerSyncManager
▼
timerStore.applyRemoteState(state)