从NotificationCenter删除/取消待处理的本地通知

时间:2019-04-15 04:30:56

标签: ios swift notifications

我有一个视图控制器,用于初始化viewDidLoad上的本地计划通知。如果用户按下按钮,我想阻止此通知的发生。

我找到了一些答案,说要使用center.removeAllPendingNotificationRequests(),但这不适用于NotificationCenter

let notificationPublisher = NotificationPublisher()

override func viewDidLoad() {

    notificationPublisher.sendNotification(title: "Test", subtitle: "", body: "Test", badge: nil, delayInterval: Int(breakTime))
}

@objc func buttonPressed() {
    // Want to dismiss the pending notification here
}

NotificationPublisher.swift:

import UIKit
import UserNotifications

class NotificationPublisher: NSObject {

    let notificationCenter = NotificationCenter.default

    func sendNotification(title: String, subtitle: String, body: String, badge: Int?, delayInterval: Int?) {

        let notificationContent = UNMutableNotificationContent()
        notificationContent.title = title
        notificationContent.subtitle = subtitle
        notificationContent.body = body

        var delayTimeTrigger: UNTimeIntervalNotificationTrigger?

        if let delayInterval = delayInterval {
            delayTimeTrigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(delayInterval), repeats: false)
        }

        if let badge = badge {
            var currentBadgeCount = UIApplication.shared.applicationIconBadgeNumber
            currentBadgeCount += badge
            notificationContent.badge = NSNumber(integerLiteral: currentBadgeCount)
        }

        notificationContent.sound = UNNotificationSound.default

        UNUserNotificationCenter.current().delegate = self

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

        UNUserNotificationCenter.current().add(request) { (error) in
            if let error = error {
                print(error.localizedDescription)
            }
        }

    }

}

extension NotificationPublisher: UNUserNotificationCenterDelegate {

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

        let identifer = response.actionIdentifier

        switch identifer {
        case UNNotificationDismissActionIdentifier:
            print("The notification was dismissed")
            completionHandler()
        case UNNotificationDefaultActionIdentifier:
            print("The user opened the app from the notification")
            completionHandler()
        default:
            print("The default case was called")
        }

    }

}

0 个答案:

没有答案