0

我正在使用以下代码向用户发送通知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 无效,但这只会给我一个错误,所以我认为这不是要走的路。执行此操作的方式是什么?:)

4

2 回答 2

0

这很简单,感谢@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)
}
于 2017-04-26T12:01:58.707 回答
0

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

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

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

于 2017-04-26T13:19:28.840 回答