Objective-C Mac OS X分布式通知iTunes

5
我需要一点帮助,我目前在我的 Mac OS X 应用程序中有一个方法 updateTrackInfo,它可以获取正在 iTunes 播放的艺术家名称、曲目名称和曲目持续时间。
然而,我希望应用程序监听分布式 iTunes 通知 com.apple.iTunes.playerInfo,每当 iTunes 发布通知时调用方法 updateTrackInfo。请问有人能帮我,在头文件和实现文件中需要编写什么内容。
谢谢,Sami。
2个回答

14
您正在寻找 -[NSDistributedNotificationCenter addObserver:selector:name:object:] 方法:
NSDistributedNotificationCenter *dnc = [NSDistributedNotificationCenter defaultCenter];
[dnc addObserver:self selector:@selector(updateTrackInfo:) name:@"com.apple.iTunes.playerInfo" object:nil];

同一类别的其他地方...

- (void) updateTrackInfo:(NSNotification *)notification {
  NSDictionary *information = [notification userInfo];
  NSLog(@"track information: %@", information);
}

甚至在通知中为您提供了许多追踪信息,那不是很好吗?


大多数情况下这很好用,但当当前歌曲被停止时,即没有当前歌曲时,它不会通知我。 - SilverWolf

3
感谢您的帮助,您帮我纠正了代码,我先前写成了这样:
- (id) init {
self = [super init];
if (!self) return nil;
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(receiveNotification:) 
                                             name:@"com.apple.iTunes.playerInfo"
                                           object:nil];
return self;}

- (void) receiveNotification:(NSNotification *) notification {
if ([@"com.apple.iTunes.playerInfo" isEqualToString:@"com.apple.iTunes.playerInfo"]) {
    NSLog (@"Successfully received the test notification!");
}}

但它使用的是NSNotificationCenter而不是NSDistributedNotificationCenter。这就是我犯错的地方。
谢谢,Sami。

1
没错,就是这样。另外需要注意的是,在你的-receiveNotification:方法中的if()语句将永远为真... - Dave DeLong

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接