使用 swift 停止通知 3

Stop a notification using swift 3

我有一个问题涉及停止本地通知。这个停止按钮是这样的,如果用户启动计时器(一旦计时器用完就会弹出通知)然后决定他们不再需要计时器,他们可以取消它。这里的问题是我尝试过的每一种方法都不能阻止通知关闭。这主要是因为方法已经过时了。下面是我的代码,我想知道是否有人对如何停止通知有任何想法。非常感谢任何帮助。

//In the view did load section
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
        if granted {
            print("granted")
        } else {
            print("not granted")
        }
    }


//in a seperate function
let center = UNUserNotificationCenter.current()

content.title = "Local notification"
content.categoryIdentifier = "alarm"
content.userInfo = ["customData": "fizzbuzz"]
content.sound = UNNotificationSound.init(named: "1.mp3")
content.badge = 1

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: time, repeats: false)
let request = UNNotificationRequest(identifier: "requestAlarm", content: content, trigger: trigger)
center.add(request)

center.delegate = self

告诉用户通知中心removeAllPendingNotificationRequests

您可以通过以下方式停止某些通知:

center.removePendingNotificationRequests(withIdentifiers: ["alarm"])

其中 "alarm" 是您的类别标识符。这样你就不会停止每一个通知,只是选择的一个。好东西。 问候。