58

Cocoa アプリから通知センターにテスト通知を送信する例を教えてください。例えば。をクリックするとNSButton

4

2 に答える 2

153

Mountain Lion の通知は 2 つのクラスで処理されます。NSUserNotificationNSUserNotificationCenterNSUserNotificationは実際の通知で、プロパティで設定できるタイトル、メッセージなどがあります。作成した通知を配信するにはdeliverNotification:、NSUserNotificationCenter で利用可能なメソッドを使用できます。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];
}

これにより、タイトルとメッセージを含む通知が生成され、表示時にデフォルトのサウンドが再生されます。これ以外にも、通知でできることはたくさんあります (通知のスケジュール設定など)。詳細については、リンク先のドキュメントを参照してください。

1 つの小さな点として、アプリケーションが主要なアプリケーションである場合にのみ、通知が表示されます。アプリケーションがキーであるかどうかに関係なく通知を表示する場合は、デリゲートを指定しNSUserNotificationCenterてデリゲート メソッドをオーバーライドし、userNotificationCenter:shouldPresentNotification:YES が返されるようにする必要があります。のドキュメントはここNSUserNotificationCenterDelegateにあります

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>
于 2012-08-05T10:05:15.930 に答える