【发布时间】:2012-08-02 15:13:33
【问题描述】:
有人可以举一个从 Cocoa 应用程序向通知中心发送测试通知的示例吗?例如。当我点击NSButton
【问题讨论】:
标签: objective-c xcode macos cocoa osx-mountain-lion
有人可以举一个从 Cocoa 应用程序向通知中心发送测试通知的示例吗?例如。当我点击NSButton
【问题讨论】:
标签: objective-c xcode macos cocoa osx-mountain-lion
Mountain Lion 中的通知由两个类处理。 NSUserNotification 和 NSUserNotificationCenter。 NSUserNotification 是您的实际通知,它具有可以通过属性设置的标题、消息等。要发送您创建的通知,您可以使用 NSUserNotificationCenter 中的deliverNotification: 方法。 Apple 文档有关于 NSUserNotification 和 NSUserNotificationCenter 的详细信息,但发布通知的基本代码如下所示:
- (IBAction)showNotification:(id)sender{
NSUserNotification *notification = [[NSUserNotification alloc] init];
notification.title = @"Hello, World!";
notification.informativeText = @"A notification";
notification.soundName = NSUserNotificationDefaultSoundName;
[[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification];
[notification release];
}
这将产生一个带有标题、消息的通知,并在显示时播放默认声音。除了这个(例如安排通知)之外,您还可以对通知做更多的事情,这在我链接到的文档中都有详细说明。
一个小点,只有当你的应用是关键应用时才会显示通知。如果您希望无论您的应用程序是否为关键应用程序都显示通知,您需要为NSUserNotificationCenter 指定一个委托并覆盖委托方法userNotificationCenter:shouldPresentNotification: 以便它返回YES。 NSUserNotificationCenterDelegate 的文档可以在 here 找到
这是一个向 NSUserNotificationCenter 提供委托然后强制显示通知的示例,无论您的应用程序是否是关键。在应用程序的 AppDelegate.m 文件中,像这样编辑它:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
[[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:self];
}
- (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center shouldPresentNotification:(NSUserNotification *)notification{
return YES;
}
并在 AppDelegate.h 中声明该类符合 NSUserNotificationCenterDelegate 协议:
@interface AppDelegate : NSObject <NSApplicationDelegate, NSUserNotificationCenterDelegate>
【讨论】:
@alexjohnj 为 Swift 5.2 更新了答案
在 AppDelegate 中
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Set delegate
NSUserNotificationCenter.default.delegate = self
}
然后向 NSUserNotificationCenterDelegate 确认为
extension AppDelegate: NSUserNotificationCenterDelegate {
func userNotificationCenter(_ center: NSUserNotificationCenter, shouldPresent notification: NSUserNotification) -> Bool {
true
}}
【讨论】: