Search code examples
swiftprintingnotificationsnotificationcenter

How can I print all notifications from NotificationCenter in SwiftUI?


For general debugging I thought it would be really useful to find out all notifications being published by NotificationCenter and print them to the console. I couldn't find a post on this so I thought I would share how I achieved this.


Solution

  • @main
    struct MyApp: App {
        let notes = NotificationObserver()
    
        var body: some Scene {
            WindowGroup {
                Text("Hello, world!")
            }
        }
    }
    
    
    class NotificationObserver {
        init() {
            NotificationCenter.default.addObserver(
                self,
                selector: #selector(printAllNotifications),
                name: nil,
                object: nil)
        }
    
        @objc func printAllNotifications(_ note: Notification) {
            guard note.name != UIScreen.brightnessDidChangeNotification else { return }
    
            print(note.name)
        }
    }
    

    Essentially the name parameter of addObserver(_:selector:name:object:) is optional, and passing nil as an argument means all notifications are observed.

    The function we provide to the selector parameter needs access to Objective-C at runtime so we mark it with @objc. Since @objc can only be used with members of classes we wrap this code in our NotificationObserver class.

    Now all we need to do is create an instance of NotificationObserver at the entry point of our app and all notifications are printed to the console (here we exclude the brightnessDidChangeNotification as this seems to pollute the console and is probably not what you're looking for when using this).