我想在用户选定的小时之间向用户显示本地通知,并且每半小时重复一次通知,直到所选小时的限制到来,并且每天重复此通知。 我使用过这段代码
let components = calendar.dateComponents(in: .current, from: date)
var triggerDate = DateComponents()
triggerDate.hour = components.hour
triggerDate.minute = components.minute
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: true)
但是这只是在用户选择的特定时间每天重复通知,但我想在特定时间每半小时重复一次。我使用了UNNotifications.Any帮助将非常感谢。谢谢
答案 0 :(得分:1)
如果要在所选时间之间每隔半小时显示本地通知,则必须为每小时设置不同的通知,并使用不同的通知标识符:
var dateStart = "Pass Your Start Date for Notification."
let dateEnd = "Pass Your End Date for Notification."
//Check Start Date is less then End Date is not.
while dateStart < dateEnd {
dateStart = dateStart.addingTimeInterval(0.5 * 60 * 60) //Add half an hour to start time
//Schedule notification With body and title.
scheduleNotification(at: dateStart, body: "Show Me", titles: "Remainder")
}
通过以下函数实施通知:
//Schedule Notification with Daily bases.
func scheduleNotification(at date: Date, body: String, titles:String) {
let triggerDaily = Calendar.current.dateComponents([.hour,.minute,.second], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)
let content = UNMutableNotificationContent()
content.title = titles
content.body = body
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "todoList"
let request = UNNotificationRequest(identifier: "NotificationAt-\(date))", content: content, trigger: trigger)
UNUserNotificationCenter.current().delegate = self
//UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UNUserNotificationCenter.current().add(request) {(error) in
if let error = error {
print("Uh oh! We had an error: \(error)")
}
}
}
在dateStart变量中传递开始Date
,在dateEnd变量中传递Date
结束日期。