0

我试图将本地通知设置为在每个月的最后一天触发,无论是 28 日、29 日、30 日还是 31 日。

使用以前的框架UILocalNotification,我可以指定fireDateandrepeatInterval并且它有效。但是现在我将框架更新为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())
4

1 回答 1

1

您可以使用以下代码,在显示通知后计算下一个最后一天月份。

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])
} }

我已经测试过了,对我来说工作正常。

于 2021-11-03T12:59:16.317 回答