在我的应用中,我想添加本地通知。方案是用户可以选择从周一到周日的任何时间和日期。例如,如果用户选择Mon,Thur和Sat作为日期和时间为晚上11:00,那么现在应该在所有选定的日期和特定时间通知用户。
代码:
let notification = UNMutableNotificationContent()
notification.title = "Danger Will Robinson"
notification.subtitle = "Something This Way Comes"
notification.body = "I need to tell you something, but first read this."
let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)
// let test = UNCalendarNotificationTrigger()
let request = UNNotificationRequest(identifier: "notification1", content: notification, trigger: notificationTrigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
我正在使用此代码,但这并不符合我的需要。
答案 0 :(得分:7)
要获取在某个特定工作日重复的本地通知,您可以使用UNCalendarNotificationTrigger
:
let notification = UNMutableNotificationContent()
notification.title = "Danger Will Robinson"
notification.subtitle = "Something This Way Comes"
notification.body = "I need to tell you something, but first read this."
// add notification for Mondays at 11:00 a.m.
var dateComponents = DateComponents()
dateComponents.weekday = 2
dateComponents.hour = 11
dateComponents.minute = 0
let notificationTrigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
let request = UNNotificationRequest(identifier: "notification1", content: notification, trigger: notificationTrigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
如果您想在星期一,星期四和星期六11:00收到通知,则需要添加3个单独的请求。为了能够删除它们,您必须跟踪标识符。