如何观察来自其他应用程序的通知?

问题描述 投票:1回答:1

我想在某个应用程序触发事件时得到通知。我不是Objective-C开发人员,也不是OS X API,所以我希望这个问题不太基本。

我的目标是将当前正在播放的歌曲的元信息写入日志文件。对于iTu​​nes,我可以使用以下Objective-C行:

[[NSDistributedNotificationCenter defaultCenter]
 addObserver: myObserver selector: @selector(observeNotification:)
 name: @"com.apple.iTunes.playerInfo" object:nil];

但是,对于AirServer(这是一个AirPlay接收器软件),我也需要它。不幸的是,以下操作不起作用-永远不会调用观察者:

[[NSDistributedNotificationCenter defaultCenter]
 addObserver: myObserver selector: @selector(observeNotification:)
 name: @"com.pratikkumar.airserver-mac" object:nil];

因此,显然,AirServer不会发送此类通知。但是,当开始播放新歌曲时,通知中心会显示一条通知。

我的下一步是在OS X通知中心中定期检查新通知(如此处所述:https://stackoverflow.com/a/25930769/1387396)。不过,这不太干净-所以我的问题是:在这种情况下,还有其他选择吗?

objective-c macos cocoa foundation airserver
1个回答
1
投票

Catalina默默地更改了addObserver的行为-您不能再使用nil的名称来观察所有通知-您必须传递名称。这使得事件名称的发现更加困难。

首先,您必须了解,虽然NSDistributedNotificationCenter中包含单词Notification;没有关系。从About Local Notifications and Remote Notifications开始,它会声明:

注意:远程通知和本地通知与广播通知(NSNotificationCenter)或键值观察通知无关。

因此,我将从NSDistributedNotificationCenter的角度回答,而不是关于远程/本地通知-在链接的答案中您已经具有潜在的解决方案,用于观察包含记录的数据库文件通知的方式。

您要做的第一件事是听正确的通知。创建一个监听所有事件的简单应用程序;例如使用:

NSDistributedNotificationCenter *center = [NSDistributedNotificationCenter defaultCenter];
[center addObserver:self
           selector:@selector(notificationEvent:)
               name:nil
             object:nil];


-(void)notificationEvent:(NSNotification *)notif {
    NSLog(@"%@", notif);
}

它表示通知是:

__CFNotification 0x6100000464b0 {name = com.airserverapp.AudioDidStart; object = com.pratikkumar.airserver-mac; userInfo = {
    ip = "2002:d55e:dbb2:1:10e0:1bfb:4e81:b481";
    remote = YES;
}}
__CFNotification 0x618000042790 {name = com.airserverapp.AudioDidStop; object = com.pratikkumar.airserver-mac; userInfo = {
    ip = "2002:d55e:dbb2:1:10e0:1bfb:4e81:b481";
    remote = YES;
}}

这表明name调用中的addObserver参数应为com.airserverapp.AudioDidStartcom.airserverapp.AudioDidStop

您可以使用类似的代码来确定所有通知,这将允许您在需要特定观察者时添加相关观察者。这可能是观察此类通知的最简单方法。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.