objective-c - 发送通知到山狮通知中心

标签 objective-c xcode macos cocoa osx-mountain-lion

有人可以举一个从 Cocoa 应用程序向通知中心发送测试通知的示例吗?例如。当我点击 NSButton

最佳答案

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

这将产生一个带有标题、消息的通知,并在显示时播放默认声音。除了这个(例如安排通知),您还可以对通知做更多的事情,这在我链接到的文档中有详细说明。

一个小点,只有当你的应用是关键应用时才会显示通知。如果您希望无论您的应用程序是否为 key 都显示通知,您需要为 NSUserNotificationCenter 指定一个委托(delegate)并覆盖委托(delegate)方法 userNotificationCenter:shouldPresentNotification:使其返回YES。 NSUserNotificationCenterDelegate 的文档位于 here

这是一个向 NSUserNotificationCenter 提供委托(delegate)然后强制显示通知的示例,无论您的应用程序是否是关键。在应用程序的 AppDelegate.m 文件中,像这样编辑它:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:self];
}

- (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center shouldPresentNotification:(NSUserNotification *)notification{
    return YES;
}

并在 AppDelegate.h 中声明该类符合 NSUserNotificationCenterDelegate 协议(protocol):

@interface AppDelegate : NSObject <NSApplicationDelegate, NSUserNotificationCenterDelegate>

关于objective-c - 发送通知到山狮通知中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11814903/

相关文章:

objective-c - 如何解决 undefined symbol 错误?

objective-c - 如何更改 Sprite 的 Z 顺序?

ios - 0 为企业分发导出应用程序时的权利

Excel for mac 隐藏功能区

windows - ffmpeg:在 Mac 上生成的 wmv 文件无法在 Windows 中播放

iphone - iOS 6 - 区分 iPhone 5 和其他设备?

iphone - 将 UITableView 的委托(delegate)/数据源与主 ViewController 分开

xcode - 执行嵌入到一行终端命令中的 Swift 代码

objective-c - 如何在 Xcode4 中构建 Droplet 应用程序?

macos - 控制 MagSafe 2 上的 LED(向检测引脚发送任意数据)