Swift通知重复弹窗异常求助:每日22点通知多次重复触发
Hey there! I see exactly what's causing those multiple duplicate notifications to pop up after the first two days—let's break it down and fix it.
The Core Issue
Looking at your code, the problem lies in how you're generating the notification request identifier:
let notificationRequest = UNNotificationRequest(identifier: "\(NSDate().timeIntervalSince1970)", content: notificationContent, trigger: notificationTrigger)
You're using a dynamic timestamp as the identifier every time this code runs. That means every time your app launches (or this code executes), you're adding a brand new repeating notification request to the system. By the third day, you've probably added 3 separate repeating triggers, and by the fourth day 4—so when 22:00 hits, all of them fire at once, resulting in multiple identical banners.
The Fix
You need to use a fixed, unique identifier for your daily notification, and ensure you don't add duplicate requests. Here's how to adjust your code:
Define a static identifier (use something descriptive and unique to this notification):
let dailyHealthNotificationID = "DailyHealthDiaryReminder"Remove existing pending requests with the same ID before adding a new one—this ensures you only ever have one repeating trigger active:
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [dailyHealthNotificationID])Create and add the request with the fixed ID:
let notificationContent = UNMutableNotificationContent() notificationContent.title = "Diary of Health" notificationContent.body = "Wie war dein Tag?" var date = DateComponents() date.hour = 22 date.minute = 0 date.second = 0 let notificationTrigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true) let notificationRequest = UNNotificationRequest(identifier: dailyHealthNotificationID, content: notificationContent, trigger: notificationTrigger) UNUserNotificationCenter.current().add(notificationRequest) { error in if let error = error { let errorString = String(format: NSLocalizedString("Unable to Add Notification Request %@, %@", comment: ""), error as CVarArg, error.localizedDescription) print(errorString) } }
Extra Tips
- Make sure this code only runs once per app launch (e.g., in
AppDelegate.application(_:didFinishLaunchingWithOptions:)or a dedicated setup function). Avoid putting it in a view controller'sviewDidLoadunless you have logic to prevent it from running multiple times. - The steps you tried (reinstalling the app, changing Bundle ID, updating iOS) didn't fix the issue because they only cleared existing requests temporarily—every time you launched the app again, your code added a new repeating trigger, leading to the same problem over time.
That should stop the duplicate notifications for good!
内容的提问来源于stack exchange,提问作者user2982195

