2012-08-05 17 views

答えて

148

Mountain Lionの通知は2つのクラスで処理されます。 NSUserNotificationおよびNSUserNotificationCenterNSUserNotificationはあなたの実際の通知です。プロパティを介して設定できるタイトルやメッセージなどがあります。作成した通知を送信するには、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]; 
} 

表示されます。これだけではなく、通知(通知のスケジュール設定など)よりもはるかに多くのことがあります。詳細については、リンク先のドキュメントをご覧ください。

小規模な点が1つあります。通知は、アプリケーションが主要アプリケーションである場合にのみ表示されます。アプリケーションがキーであるかどうかにかかわらず通知を表示するには、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

+3

@ haseo98うん、私はちょうど私の答えに例を追加しました。 – alexjohnj

+0

メソッドのapplicationdidfinishlaunchingセクションの次にエラーが発生しました。互換性のないタイプ 'id 'のパラメータに 'AppDelegate * const __strong'を送信しています。何か案は? – haseo98

関連する問題