Повторите интервал для UNNotification - PullRequest
0 голосов
/ 07 января 2019

Существует возможность установить интервал повторения для UILocalNotification. Так как Apple устарела UILocalNotification и рекомендует вместо этого использовать UNNotification, я не смог найти способ установить уведомление с пользовательским интервалом повторения с помощью UNNotification.

    var comp = DateComponents()
    comp.year = 2019
    comp.month = 1
    comp.day = 9
    comp.hour = 14
    comp.minute = 14
    comp.second = 0
    let calendar = Calendar.current
    let notification: UILocalNotification = UILocalNotification()
    notification.category = "Daily Quote"
    notification.alertBody = "Body"
    notification.alertTitle = "Title"
    notification.fireDate = calendar.date(from: comp)
    notification.repeatInterval = NSCalendar.Unit.day
    UIApplication.shared.scheduleLocalNotification(notification)

Так можно ли установить подобное уведомление, которое повторяется ежечасно или ежедневно после ожидания первоначального уведомления с использованием нового уведомления UNNotification?

Ответы [ 2 ]

0 голосов
/ 07 января 2019

вы должны использовать UNTimeIntervalNotificationTrigger Проверьте документ https://developer.apple.com/documentation/usernotifications/untimeintervalnotificationtrigger

0 голосов
/ 07 января 2019

Чтобы имитировать API UILocalNotification fireDate и repeatInterval, вы можете создать два триггера, один неповторяющийся, который будет использоваться для начала fireDate, а другой - для repeatInterval.

Вот пример:

import UserNotifications

/// Schedules notificaiton to fire at specific date, and then it repeats by specified repeat component
/// (week, day, hour, etc.) and repeat interval. For example to repeat every 20minutes repeatComponent
/// would be .minute and repeatInterval would be 20.
/// - Parameters:
///   - fireDate: Date for initial notification delivery
///   - repeatComponent: Component by which repeating would be performed (week, day, hour, etc.)
///   - repeatInterval: Interval by which repeating by specified component would be performed. Defaults value is 1.
func scheduleNotification(fireDate: Date, repeatComponent: Calendar.Component, repeatInterval: Int = 1) {

    let content = UNMutableNotificationContent()
    content.title = "Daily Quote"
    content.body = "Inspirational quote."
    content.categoryIdentifier = "quote.category"

    UNUserNotificationCenter.current().requestAuthorization(
        options: [.alert,.sound])
    {
        (granted, error) in

        if let error = error {
            print("granted, but Error in notification permission:\(error.localizedDescription)")
        }

        let fireTrigger = UNTimeIntervalNotificationTrigger(timeInterval: fireDate.timeIntervalSinceNow, repeats: false)

        let fireDateRequest = UNNotificationRequest(identifier: "quote.starter", content: content, trigger: fireTrigger)

        UNUserNotificationCenter.current().add(fireDateRequest) {(error) in
            if let error = error {
                print("Error adding firing notification: \(error.localizedDescription)")
            } else {

                if let firstRepeatingDate = Calendar.current.date(byAdding: repeatComponent, value: repeatInterval, to: fireDate) {

                    let repeatingTrigger = UNTimeIntervalNotificationTrigger(timeInterval: firstRepeatingDate.timeIntervalSinceNow, repeats: true)

                    let repeatingRequest = UNNotificationRequest(identifier: "quote.repeater", content: content, trigger: repeatingTrigger)

                    UNUserNotificationCenter.current().add(repeatingRequest) { (error) in
                        if let error = error {
                            print("Error adding repeating notification: \(error.localizedDescription)")
                        } else {
                            print("Successfully scheduled")
                            // Successfully scheduled
                        }
                    }

                }
            }
        }

        UNUserNotificationCenter.current().delegate = self
    }
}

Делегат (для отладки):

extension ViewController: UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        print("\(notification.request.identifier): \(Date())")
        UNUserNotificationCenter.current().getPendingNotificationRequests { (requests) in
            for request in requests {
                if let timeIntervalTrigger = request.trigger as? UNTimeIntervalNotificationTrigger {
                    print(Date(timeIntervalSinceNow: timeIntervalTrigger.timeInterval))
                }

            }
        }
    }
}

Использование по вашему требованию:

let interval = 7 // One week from now
if let fireDate = Calendar.current.date(byAdding: .day, value: interval, to: Date()) {
    _ = scheduleNotification(fireDate: fireDate, repeatComponent: .day)
}

Примечание

Указание повторяющегося интервала менее 60 секунд приведет к исключению:

«NSInternalInconsistencyException», причина: «интервал времени должен быть не менее 60 при повторении»

...