再次发送通知

时间:2017-04-24 12:37:23

标签: ios swift unusernotificationcenter

我使用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无效,但这只给了我一个错误,所以我不认为这是要走的路。做这个动作的方法是什么? :)

2 个答案:

答案 0 :(得分: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)
}

答案 1 :(得分:0)

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

  

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

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