現象描述
設置 10:00 觸發的 `UNNotificationRequest`,除預期時間外,其他整點(如 11:00、12:00)也會重複彈出通知。
常見原因與檢查清單
- 重複添加請求:每次 App 啟動/進入前台調用 `addNotificationRequest` 且未檢查是否已存在,導致堆疊多個相同標識符的請求。
// 正確:先移除舊請求
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: ["daily_10am"])
// 再添加新請求
center.add(request) { error in ... }
- 觸發器類型錯誤:使用 `UNCalendarNotificationTrigger` 但 `repeats: true` 且 `dateComponents` 僅設置 `hour=10`,未設置 `minute=0`,系統可能按分鐘匹配觸發。
var comps = DateComponents()
comps.hour = 10
comps.minute = 0 // 必須顯式設置分鐘,否則默認 0 但邏輯易誤解
let trigger = UNCalendarNotificationTrigger(dateMatching: comps, repeats: true)
- 時區/日曆不一致:`DateComponents` 默認使用用戶當前時區,若服務器下發 UTC 時間未正確轉換,會導致偏移觸發。
- 推送通知幹擾:遠程推送 (APNs) payload 中包含 `content-available: 1` 觸發靜默推送,被誤判為本地通知。
調試技巧
- Xcode 控制台過濾 `UserNotifications` 關鍵字,查看實際調度時間。
- 調用 `center.getPendingNotificationRequests { requests in ... }` 打印所有待發送請求的 `identifier`、`trigger.nextTriggerDate()` 核對。