Set local notifications for particular days and ti

2019-05-22 06:10发布

In my app, i want to add local notifications. The scenario will be that the user can select any time and days from Mon to Sun. For example, if the user selects Mon, Thur and Sat as days and time as 11:00 pm, so now the user should be notified at all the selected days and that particular time.

Code:

 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)

I am using this code but this doesn't work according to what I need.

1条回答
Viruses.
2楼-- · 2019-05-22 06:14

To get local notifications that repeat on a certain weekday at a certain time you can use a 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)

If you want notifications on Monday, Thursday and Saturday at 11:00 you need to add 3 separate requests. To be able to remove them you have to keep track of the identifiers.

查看更多
登录 后发表回答