OSX Desktop Notifications

Johan Attali bio photo By Johan Attali

Creating desktop notifications for OSX is easy and involves only two classes NSUserNotification and NSUserNotificationCenter added for Mountain Lion (10.8).

You start by creating a NSUserNotification and then use the deliverNotification: method of NSUserNotificationCenter to dispatch it.

- (void)mainButtonTouched:(id)sender {
    NSUserNotification* notification = [[NSUserNotification alloc] init];
    notification.title = @"Title";
    notification.informativeText = @"Text displayed in the notification";
    notification.soundName = NSUserNotificationDefaultSoundName;

    [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification];
}

However if the application is the current application in use, you won't see the notification popup in your desktop, which could lead to a tough time testing it. If you want to override this default behaviour set a delegate to the [NSUserNotificationCenter defaultUserNotificationCenter] and override the method

- (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center shouldPresentNotification:(NSUserNotification *)notification`

Full example here:

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Insert code here to initialize your application
    [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:self];
}

- (void)mainButtonTouched:(id)sender {
    NSUserNotification* notification = [[NSUserNotification alloc] init];
    notification.title = @"ChonChon";
    notification.informativeText = @"Cacato Bouli";
    notification.soundName = NSUserNotificationDefaultSoundName;


    [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification];
}

#pragma mark - NSUserNotificationCenterDelegate

- (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center shouldPresentNotification:(NSUserNotification *)notification {
    return YES;
}

@end