首页 > 解决方案 > 如何在 Swift 5 中使用 UNTimeIntervalNotificationTrigger 停止 UNUserNotificationCenter?

问题描述

我有一个 UNUserNotificationCenter 每 60 秒发送一次本地通知。它的实现如下:

    let userNotificationCenter = UNUserNotificationCenter.current()
    let notificationContent = UNMutableNotificationContent()
    notificationContent.title = "Test title"
    notificationContent.body = "Test body"

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60,
                                                    repeats: true)

    let request = UNNotificationRequest(identifier: "testNotification",
                                        content: notificationContent,
                                        trigger: trigger)

    userNotificationCenter.add(request) { (error) in
        if let error = error {
            print("Notification Error: ", error)
        }
    }

它运行良好,但我无法停止它,即使我的应用程序被杀死,它也会继续发送通知。

在这种情况下,阻止 UNUserNotificationCenter 发送通知的最佳方法是什么?

标签: iosswiftunusernotificationcenter

解决方案


您只需调用removePendingNotificationRequests(withIdentifiers:)并传入您需要取消已安排但未发送的通知的标识符。

userNotificationCenter.removePendingNotificationRequests(withIdentifiers: ["testNotification"])

或者,如果您想删除应用程序的所有待处理通知,您可以调用removeAllPendingNotificationRequests()


推荐阅读