NSUserNotificationCenter解除通知

Bin*_*cks 20 cocoa nsnotificationcenter osx-mountain-lion nsusernotification

我正在尝试将新的Mountain Lion NSUserNotificationCenter用于我的应用程序(实际上并不太难).发布通知就像魅力一样

NSUserNotification *userNotification = [[NSUserNotification alloc] init];
userNotification.title = @"Some title";
userNotification.informativeText = @"Some text";

[[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:userNotification];
Run Code Online (Sandbox Code Playgroud)

但是,一旦应用获得焦点,我想解除屏幕上的所有通知.就像新的消息应用程序一样.在后台接收新消息时,会显示通知.当应用程序再次变为活动状态时,这些应用程序将自动关闭并从屏幕和通知中心消失.

为了复制这个,我已经为NSApplicationDidBecomeActiveNotification通知注册了一个方法,该方法也被成功调用.我在那里打电话[NSUserNotificationCenter defaultUserNotificationCenter] removeAllDeliveredNotifications].

但是,这会导致删除通知中心中收集的通知,同时仍显示右上角显示的相应"气泡".

迭代所有已发送的通知并逐个删除它们具有完全相同的效果,scheduleNotification而不是使用deliverNotification.

我是唯一遇到此问题的人,还是我错过了以编程方式解除屏幕上部分和通知中心部分通知的内容?

0xc*_*ced 18

消息应用程序可能正在使用私有NSUserNotificationCenter _removeAllDisplayedNotifications_removeDisplayedNotification:方法.

您可以尝试使用这些方法来测试这是否是您正在寻找的.只需添加此类别接口即可声明方法:

@interface NSUserNotificationCenter (Private)
- (void)_removeAllDisplayedNotifications;
- (void)_removeDisplayedNotification:(NSUserNotification *)notification;
@end
Run Code Online (Sandbox Code Playgroud)

不幸的是,由于这些是未记录的方法,因此您无法在通过App Store分发的应用程序中使用它们.如果这确实是您正在寻找的,那么您应该提交一个错误并要求这些方法成为公共API的一部分.