【发布时间】:2017-03-30 04:17:00
【问题描述】:
我注意到,如果我创建一个带有自定义日期的UNCalendarNotificationTrigger,除非我输入以下内容,否则它不会被添加:
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: **true**)
苹果的例子是:
let date = DateComponents()
date.hour = 8
date.minute = 30
let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)
重复是有意义的 == true。
在我的场景中,我不需要创建一个重复多次的通知,但我需要在特定日历日期(当然是在未来)仅触发一次的多个通知..
如果我在做:
let calendar = Calendar(identifier: .gregorian)
let formatter = DateFormatter()
formatter.dateFormat = "yyyyMMdd"
let newdate = formatter.date(from: "20161201")
let components = calendar.dateComponents(in: .current, from: newdate!)
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)
然后我总是收到 0 个待处理通知...
UNUserNotificationCenter.current().getPendingNotificationRequests(completionHandler: { (notifications) in
print("num of pending notifications \(notifications.count)")
})
num of pending notification 0
有什么想法吗?
EDIT1: 添加答案之一指出的其他上下文。 我实际上是在将请求添加到当前的 UNUserNotificationQueue。
let request = UNNotificationRequest(identifier: "future_calendar_event_\(date_yyyyMMdd)", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
// Do something with error
print(error.localizedDescription)
} else {
print("adding \((request.trigger as! UNCalendarNotificationTrigger).dateComponents.date)")
}
}
【问题讨论】: