NSUserNotification - 单击时如何打开应用程序

AnA*_*ice 10 macos cocoa objective-c nsusernotification

我正在使用NSUserNotification来显示通知.这工作正常.问题是当您点击通知时:

  1. 应用程序通知不会从通知中心删除.
  2. 应用程序(最小化时)无法打开.

任何熟悉NSUserNotification的人都可以提供一些指示吗?

notice.m

#import "Notice.h"

@implementation Notice

- (void) notify:(NSDictionary *)message {

    NSLog(@"Notification - Show it");

    NSUserNotification *notification = [[NSUserNotification alloc] init];
    [notification setTitle:[message valueForKey:@"title"]];
    [notification setInformativeText:[message valueForKey:@"content"]];
    [notification setDeliveryDate:[NSDate dateWithTimeInterval:0 sinceDate:[NSDate date]]];
    [notification setSoundName:NSUserNotificationDefaultSoundName];
    NSUserNotificationCenter *center = [NSUserNotificationCenter defaultUserNotificationCenter];
    [center scheduleNotification:notification];
}

- (void) userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification
{

    NSLog(@"Notification - Clicked");

    notification=nil;
    [center removeDeliveredNotification: notification];
}







#pragma mark WebScripting Protocol

+ (BOOL) isSelectorExcludedFromWebScript:(SEL)selector
{
    if (selector == @selector(notify:))
        return NO;

    return YES;
}

+ (NSString*) webScriptNameForSelector:(SEL)selector
{
    id  result = nil;

    if (selector == @selector(notify:)) {
        result = @"notify";
    }

    return result;
}

// right now exclude all properties (eg keys)
+ (BOOL) isKeyExcludedFromWebScript:(const char*)name
{
    return YES;
}

@end
Run Code Online (Sandbox Code Playgroud)

谢谢

Ram*_*uri 11

只需实现NSUserNotificationCenterDelegate并定义此方法:

- (void)userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification
Run Code Online (Sandbox Code Playgroud)

例:

这就是我在"通知程序"应用程序中所做的.

- (void) userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification
{
    NSRunAlertPanel([notification title], [notification informativeText], @"Ok", nil, nil);
}

- (void) userNotificationCenter:(NSUserNotificationCenter *)center didDeliverNotification:(NSUserNotification *)notification
{
    notifications=nil;
    [tableView reloadData];
    [center removeDeliveredNotification: notification];
}
Run Code Online (Sandbox Code Playgroud)

当通知被激活时(由用户点击)我只是通过面板通知用户(我可以使用hud窗口).在这种情况下,我立即删除已发送的通知,但这不是通常发生的情况.通知可能会停留有一段时间,并在半小时后被删除(这取决于您正在开发的应用程序).

  • 不要忘记将自己设置为代表.如果你从未在任何时候真正成为代表,那么特别向任何人声明你可以成为一名代表. (5认同)