Mountain Lion notifications are handled by two classes. NSUserNotification and NSUserNotificationCenter . NSUserNotification is your actual notification, it has a header, message, etc. that can be set through properties. To provide the generated notification, you can use the deliverNotification: method, available in NSUserNotificationCenter. Apple docs contain detailed information about NSUserNotification and NSUserNotificationCenter , but the basic code for sending a notification is as follows:
- (IBAction)showNotification:(id)sender{ NSUserNotification *notification = [[NSUserNotification alloc] init]; notification.title = @"Hello, World!"; notification.informativeText = @"A notification"; notification.soundName = NSUserNotificationDefaultSoundName; [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification]; }
This will result in a notification with a heading, message and will play the default sound when it is displayed. There is much more that you can do with notifications than just this (for example, planning notifications), and all this is described in detail in the documentation to which I am attached.
One small point, notifications will only be displayed when your application is a key application. If you want your notifications to be displayed regardless of whether your application is key or not, you need to specify a delegate for NSUserNotificationCenter and override the delegate method userNotificationCenter:shouldPresentNotification: so that it returns YES. The documentation for NSUserNotificationCenterDelegate can be found here.
Here's an example of providing a delegate to NSUserNotificationCenter, and then forcing the display of notifications regardless of whether your application is key. In the AppDelegate.m application file, edit it as follows:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:self]; } - (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center shouldPresentNotification:(NSUserNotification *)notification{ return YES; }
And in AppDelegate.h, declare that the class conforms to the NSUserNotificationCenterDelegate protocol:
@interface AppDelegate : NSObject <NSApplicationDelegate, NSUserNotificationCenterDelegate>
alexjohnj Aug 05 '12 at 10:05 2012-08-05 10:05
source share