2012-08-05 31 views

回答

148

在山狮的通知由两个类处理。 NSUserNotificationNSUserNotificationCenterNSUserNotification是您的实际通知,它有一个标题,一条消息等可以通过属性设置。要传递您创建的通知,您可以使用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]; 
} 

这会产生一个通知,一个标题,一个消息,那会打的时候默认的声音它被显示。还有更多的事情可以通过通知来完成(比如计划通知),这些都在我链接的文档中详细说明。

一个小问题,只有当你的应用程序是关键应用程序时才会显示通知。如果您希望显示通知而不管应用程序是否为关键字,则需要指定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> 
+0

你能如何覆盖userNotificationCenter阐述? (对不起,我真的很陌生:)) – haseo98 2012-08-05 12:50:04

+3

@ haseo98是的,我刚刚给我的答案加了一个例子。 – alexjohnj 2012-08-05 13:10:49

+0

Im在方法的applicationdidfinishlaunching部分旁边发生错误,将'AppDelegate * const __strong'发送到不兼容类型'id '的参数。有任何想法吗? – haseo98 2012-08-05 13:25:47