【问题标题】:how to set notifications at custom intervals between custom start and end times如何在自定义开始和结束时间之间的自定义间隔设置通知
【发布时间】:2020-05-08 14:46:13
【问题描述】:

所以我问了一个类似的问题,但这超出了该问题的范围。我想为用户提供自定义通知何时开始和结束的选项;然后他们会选择通知的间隔。

上一个问题: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】:

    如果您对如何更好地做到这一点有任何其他建议,请告诉我。

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

    【讨论】:

      猜你喜欢
      • 2015-11-30
      • 2011-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多