Удалить / отменить ожидающие локальные уведомления из NotificationCenter - PullRequest
2 голосов
/ 15 апреля 2019

У меня есть контроллер представления, который инициализирует локальное запланированное уведомление о 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")
        }

    }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...