问题描述
是否可以侦听/观察macOS收到的新通知?
Is it possible to listen/observe for new notifications macOS receives?
我的意思是就像收到新的iMessage或Slack消息一样(基本上所有导致NotificationCenter显示通知的东西)
I mean like when a new iMessage or a Slack message is received (so basically everything that causes NotificationCenter to display a Notification)
推荐答案
简短答案:这是不可能的.
Short answer: It is not possible.
除非应用程序提供特定的API,否则您将无法观察到应用程序发送的用户通知.例如,iMessage和Mail的AppleScript词典包含脚本可以响应的事件.但是,用户通知封装在目标应用程序中.
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.
有一个名为 DistributedNotificationCenter 的全局通知类,通知调度可以跨任务边界广播通知的机制.一些进程正在发送分布式通知,但它与UserNotification
完全不同.例如,TimeMachine引擎进程backupd
在运行备份时发送分布式通知.
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.
您可以使用
DistributedNotificationCenter.default().addObserver(self, selector: #selector(handleNotifications(_:)), name: nil, object: nil)
但是我怀疑iMessage在收到消息时会发送分布式通知.
but I doubt that iMessage sends a distributed notification when a message is received.
这篇关于观察新的系统通知OSX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!