'What would be the best way to delete pending notifications after the user turned off and turned back ON local notifications - SwiftUI

I have an app that uses local notifications and everything is working fine, but I was wondering what could happen with pending notifications that are never triggered. For instance, if a notification is scheduled to be triggered today but the user turned off notifications for the app sometime before today, at that point the notification will never trigger. I would like to be able to delete all pending notifications when the user turns notifications back on again.

What would be the best way to call the deleteAllPendingNotifications method when the user turns OFF and turns back ON notifications again?

I tried calling it on the onAppear method but this will only work if the user is in the ContentView when he/she turns On/Off notifications.

    struct ContentView: View {
        var body: some View {
            Form {
                // some textFields
            }
            .onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)){ _ in
                notificationsManager.deleteAllPendingNotifications()
            }
        }
    }

Notifications Manager Class:

    class NotificationsManager{

        func deleteAllPendingNotifications(){
            UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
        }

        func createNotification(notificationDate: Date){
            UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
                if success {
                    let calendar = Calendar(identifier: .gregorian)
                    
                    let components = calendar.dateComponents([.month, .day, .hour, .minute, .second], from: notificationDate)

                    let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)

                    let content = UNMutableNotificationContent()
                    content.title = "Notification Title"
                    content.body = "Notification message!"
                    content.categoryIdentifier = "someCategoryID"
                    content.sound = UNNotificationSound.default
                    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)

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


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source