再次发送通知

Send notification again

我使用 UNTimeIntervalNotificationTrigger 通过以下代码向用户发送通知。通知在 1 小时后发送,有效。现在我想让用户能够重置通知的 TimeInterval,以便再次运行相同的通知,但 TimeInterval 仅在用户按下此按钮时重置。这意味着 repeats: true 不是一个选项。

我的代码:

let tijd = 15

@IBAction func change(_ sender: Any) {
    // Notification
    let content = UNMutableNotificationContent()
    content.title = "title"
    content.body = "body"
    content.badge = 1
    content.sound = UNNotificationSound.default()


    // Timer
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(tijd), repeats: false)
    let request = UNNotificationRequest(identifier: bezigheid, content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}

@IBAction func repeat(_ sender: Any) {
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(tijd), repeats: false)
    trigger.invalidate()
}

我尝试在单击重复按钮时使 TimeInterval 无效,但这只会给我一个错误,所以我认为这不是可行的方法。执行此操作的方式是什么? :)

这很简单,感谢@KKRocks 我能够找到解决方案。我只需要删除它并再次添加相同的通知,请参阅代码:

let tijd = 15

@IBAction func change(_ sender: Any) {
    // Notification
    let content = UNMutableNotificationContent()
    content.title = "title"
    content.body = "body"
    content.badge = 1
    content.sound = UNNotificationSound.default()

    // Timer
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(tijd), repeats: false)
    let request = UNNotificationRequest(identifier: bezigheid, content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}

@IBAction func repeat(_ sender: Any) {     
    // Remove notification
    UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [bezigheid])

    // Notification
    let content = UNMutableNotificationContent()
    content.title = "title"
    content.body = "body"
    content.badge = 1
    content.sound = UNNotificationSound.default()

    // Timer
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(tijd), repeats: false)
    let request = UNNotificationRequest(identifier: bezigheid, content: content, trigger: trigger)

    // Add notification
    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}

首先使用以下代码删除旧通知://删除通知

UNUserNotificationCenter.current().removePendingNotification‌​Requests(withIdentif‌​iers: [bezigheid])

然后您可以像设置第一个通知一样设置下一个通知!