has*_*o98 56 macos xcode cocoa objective-c osx-mountain-lion
有人可以举例说明从Cocoa应用程序向通知中心发送测试通知吗?例如.当我点击一个NSButton
ale*_*hnj 152
Mountain Lion中的通知由两个类处理.NSUserNotification和NSUserNotificationCenter.NSUserNotification是您的实际通知,它有标题,消息等可以通过属性设置.要发送您已创建的通知,可以使用deliverNotification:NSUserNotificationCenter中提供的方法.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];
}
Run Code Online (Sandbox Code Playgroud)
这将产生带有标题,消息的通知,并且在显示时将播放默认声音.您可以使用通知进行更多操作(例如调度通知),这些都在我链接到的文档中详细说明.
一个小点,通知只会在您的应用程序是关键应用程序时显示.如果您希望显示通知,无论您的应用程序是否为密钥,您都需要指定一个委托NSUserNotificationCenter并覆盖委托方法,userNotificationCenter:shouldPresentNotification:以便它返回YES.NSUserNotificationCenterDelegate可以在此处找到文档
以下是向NSUserNotificationCenter提供委托,然后强制显示通知的示例,无论您的应用程序是否为密钥.在应用程序的AppDelegate.m文件中,编辑它:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
[[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:self];
}
- (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center shouldPresentNotification:(NSUserNotification *)notification{
return YES;
}
Run Code Online (Sandbox Code Playgroud)
在AppDelegate.h中,声明该类符合NSUserNotificationCenterDelegate协议:
@interface AppDelegate : NSObject <NSApplicationDelegate, NSUserNotificationCenterDelegate>
Run Code Online (Sandbox Code Playgroud)