macosnotificationsmacos-sierramessage

Observe for new System Notifications OSX


Is it possible to listen/observe for new notifications macOS receives?

I mean like when a new iMessage or a Slack message is received (so basically everything that causes NotificationCenter to display a Notification)


Solution

  • Short answer: It is not possible.

    You can't observe user notifications sent by applications unless an application provides a specific API. For example the AppleScript dictionary of iMessage and Mail contains events scripts can respond to. However user notifications are encapsulated in the target application.


    There is a global notification class named DistributedNotificationCenter, a notification dispatch mechanism that enables the broadcast of notifications across task boundaries. Some processes are sending distributed notifications but it's a completely different functionality as UserNotification. For example the TimeMachine engine process backupd sends distributed notifications while running a backup.

    You can subscribe for all distributed notifications with

    DistributedNotificationCenter.default().addObserver(self, selector: #selector(handleNotifications(_:)), name: nil, object: nil)
    

    but I doubt that iMessage sends a distributed notification when a message is received.