【问题标题】:Send notification to Mountain lion notification center发送通知到山狮通知中心
【发布时间】:2012-08-02 15:13:33
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    Mountain Lion 中的通知由两个类处理。 NSUserNotificationNSUserNotificationCenterNSUserNotification 是您的实际通知,它具有可以通过属性设置的标题、消息等。要发送您创建的通知,您可以使用 NSUserNotificationCenter 中的deliverNotification: 方法。 Apple 文档有关于 NSUserNotificationNSUserNotificationCenter 的详细信息,但发布通知的基本代码如下所示:

    - (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>
    

    【讨论】:

    • 能否详细说明如何覆盖 userNotificationCenter? (对不起,我真的很陌生:))
    • @haseo98 是的,我刚刚在我的答案中添加了一个示例。
    • 我在方法的 applicationdidfinishlaunching 部分旁边收到错误,将“AppDelegate *const __strong”发送到不兼容类型“id”的参数。有什么想法吗?
    • @haseo98 哎呀,忘了说您需要声明您的 AppDelegate 符合 NSUserNotificationCenterDelegate 协议。检查更新的答案。
    • 感谢您的帮助,我真的很困惑如何让它在应用程序处于前台时显示通知,这解释了它。仍然不确定我是否想在我的应用中使用该功能,但至少我现在知道怎么做!
    【解决方案2】:

    @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
    }}
    

    【讨论】:

      猜你喜欢
      • 2012-07-27
      • 1970-01-01
      • 2012-07-25
      • 1970-01-01
      • 2021-06-01
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 2017-02-24
      相关资源
      最近更新 更多