[英]How to Set repeat interval as well as fire date in UNNotificationRequest
[英]How to set a local notification to fire on the last day of each month using UNNotificationRequest?
我試圖將本地通知設置為在每個月的最后一天觸發,無論是 28 日、29 日、30 日還是 31 日。
使用以前的框架UILocalNotification
我可以指定fireDate
和repeatInterval
並且它起作用了。 但是現在我正在將框架更新為UNNotofication
,我嘗試使用UNCalendarNotificationTrigger
並將DateComponents
的日期設置為0
。 然而它並沒有火。 我做錯了什么嗎? 謝謝!
代碼如下。 nextTriggerDate
為零。
var components = DateComponents()
components.hour = 8
components.minute = 0
components.day = 0
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)
print(trigger.nextTriggerDate())
您可以使用以下代碼,在顯示通知后計算下一個最后一天的月份。
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge])
{ (granted, error) in
// Enable or disable features based on authorization
}
let current = UNUserNotificationCenter.current()
current.delegate = self
setNotificationRequest()
}
func setNotificationRequest(offset: Int = 0) {
let content = UNMutableNotificationContent()
content.title = "Alarm"
content.body = "Alarm for End of Month"
content.sound = UNNotificationSound.default
var dateCompo = DateComponents()
dateCompo.day = lastDay(offset: offset)
let trigger = UNCalendarNotificationTrigger.init(dateMatching: dateCompo, repeats: true)
let request = UNNotificationRequest(identifier: "alarm-id", content: content, trigger: trigger)
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UNUserNotificationCenter.current().add(request)
}
func lastDay(offset: Int) -> Int {
let cal = Calendar.current
let m = cal.component(.month, from: Date()) + 1
let y = cal.component(.year, from: Date())
var comps = DateComponents(calendar: cal, year: y, month: m)
comps.setValue(m + 1, for: .month)
comps.setValue(0, for: .day)
let date = cal.date(from: comps)!
return cal.component(.day, from: date)
} }
extension ViewController: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// offset is set to 1 as we want to get last of next month now.
setNotificationRequest(offset: 1)
completionHandler([.badge, .sound])
} }
我已經測試過了,對我來說工作正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.