Mountain Lion中的通知由两个类处理.NSUserNotification
和NSUserNotificationCenter
.NSUserNotification
是您的实际通知,它有一个标题、一条消息等,可以通过属性设置.要传递已创建的通知,可以使用NSUserNotificationCenter中提供的deliverNotification:
方法.苹果文档中有关于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>