как настроить уведомления с настраиваемыми интервалами между настраиваемым временем начала и окончания - PullRequest
0 голосов
/ 08 мая 2020

Итак, я задал аналогичный вопрос, но это выходит за рамки этого вопроса. Я хочу дать пользователю возможность настроить, когда уведомления должны начинаться и заканчиваться; затем они будут выбирать интервалы уведомлений.

предыдущий вопрос: как установить локальные уведомления между 8:00 и 20:00 каждый день

Это функция, которую я использую сейчас и был предоставлен @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)
    }

1 Ответ

0 голосов
/ 08 мая 2020

Я исправил это, сделав это, если у вас есть другие предложения, как это сделать лучше, дайте мне знать.

    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)
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...