如何在自定义开始时间和结束时间之间的自定义间隔设置通知

问题描述 投票:0回答:1

所以我问了类似的问题,但这不在该问题的范围内。我想让用户可以选择自定义通知的开始和结束时间。然后他们将选择通知间隔。

上一个问题:how to set local notifications between 8am and 8pm every day

这是我现在正在使用的功能,由@Robert Crabtree提供:

let notificationCenter = UNUserNotificationCenter.current()
    notificationCenter.removeAllDeliveredNotifications()
    notificationCenter.removeAllPendingNotificationRequests()

    let startHour = 7
    let endHour = 23

    let totalHours = endHour - startHour
    let totalNotifications = totalHours * 2

    for i in 0...totalNotifications {
        var date = DateComponents()
        date.hour = startHour + i / 2
        date.minute = 30 * (i % 2)
        print("setting reminder for \(date.hour!):\(date.minute!)")

        let notification = UNMutableNotificationContent()
        notification.title = reminderMessages[randomInt].title
        notification.body  = reminderMessages[randomInt].body

        let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)
        let uuidString = UUID().uuidString
        let request = UNNotificationRequest(identifier: uuidString, content: notification, trigger: trigger)
        notificationCenter.add(request, withCompletionHandler: nil)
    }
swift notifications intervals unusernotificationcenter
1个回答
0
投票

如果您有其他关于如何更好地做到这一点的建议,我已通过此方法进行修复,请告诉我。

    let notificationCenter = UNUserNotificationCenter.current()
    notificationCenter.removeAllDeliveredNotifications()
    notificationCenter.removeAllPendingNotificationRequests()

    let startHour = 7
    let endHour   = 23
    let intervals = 20

    let totalHours = endHour - startHour
    let totalNotifications = totalHours * 60 / intervals

    for i in 0...totalNotifications {
        var date = DateComponents()
        date.hour = startHour + (intervals * i) / 60
        date.minute = (intervals * i) % 60
        print("setting reminder for \(date.hour!):\(date.minute!)")
        let notification = getReminder()

        let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)
        let uuidString = UUID().uuidString
        let request = UNNotificationRequest(identifier: uuidString, content: notification, trigger: trigger)
        notificationCenter.add(request, withCompletionHandler: nil)
    }
© www.soinside.com 2019 - 2024. All rights reserved.