ios - 无法通过 UNUserNotificationCenter 获得重复的每日通知以显示
问题描述
我的目标是设置一个重复的每日提醒通知。以下代码始终成功显示一次通知,但不会重复,尽管repeat: true
在代码中进行了设置。
整个通知代码如下:
let notificationID = "daily_sleep_alarm"
let title = "Rest your weary eyes"
let body = "It's bedtime. The comfort of your blanket beckons you."
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [notificationID])
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.categoryIdentifier = "daily_sleep_alarm"
content.userInfo = ["customData": "fizzbuzz"]
content.sound = nil
var dateComponents = DateComponents()
dateComponents.hour = hourSelected
dateComponents.minute = minuteSelected
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
let request = UNNotificationRequest(identifier: notificationID, content: content, trigger: trigger)
center.add(request)
如上所述,此代码一次后无法成功显示通知。我没有其他代码可以清除带有此特定notificationID
.
在应用程序启动时,我还会查看可用的待处理通知center.getPendingNotificationRequests
,它始终显示为无。
任何关于我需要做什么来正确设置每日重复通知的见解都非常感谢。
解决方案
我只是每天使用这些简单的代码行
func setNotifications(with interval: TimeInterval) {
let content = UNMutableNotificationContent()
content.title = "Tittle"
content.subtitle = "Subtle"
content.body = "Don't forget yourself!"
content.badge = 1
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: interval,
repeats: true)
let requestIdentifier = "demoNotification"
let request = UNNotificationRequest(identifier: requestIdentifier,
content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request,
withCompletionHandler: { (error) in
// Handle error
})
}