Set local notifications for particular days and time swift 3

独自空忆成欢 提交于 2019-12-22 11:35:43

问题


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:


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.



来源:https://stackoverflow.com/questions/46088774/set-local-notifications-for-particular-days-and-time-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!