Thursday, January 31, 2013

Playing system sounds

Many apps in Mac OS X use system sounds to notify user about some actions, e.g. operation is finished successfully or failure. Sound can be easily played using NSSound class:
[[NSSound soundNamed:@"Hero"] play];
The above code plays Hero sound. The problem is where to find the list of all these system sounds. They can be found in the following directory.
/System/Library/Sounds
Here the list of sounds found in that directory:
Basso
Blow
Bottle
Frog
Funk
Glass
Hero
Morse
Ping
Pop
Purr
Sosumi
Submarine
Tink 

Introduction to User Notifications in Mac OS X Mountain Lion


In Mac OS X 10.8 (Mountain Lion) Apple introduced User Notifications. They are displayed in the notification center. They can also be displayed as small popup message.


Displaying such a notification is quite easy. Cocoa Framework provides NSUserNotification class. The following code shows a usage example:

NSUserNotification *notification = [[NSUserNotification alloc] init];
notification.title = @"Hello, World!";
notification.informativeText = [NSString stringWithFormat:@"details details details"];
notification.soundName = NSUserNotificationDefaultSoundName;
[[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification];

That should display a notification in the Notification Center. What about the popup message? It's not displayed by default. To display it, there must
be implemented NSUserNotificationCenterDelegate protocol. In the example I've created, I implemented it in my AppDelegate class. The method we need is called userNotificationCenter:shouldPresentNotification:. Here is an example of its implementation:

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

Of course, we need to set a class as a delegate of the NSUserNotificationCenter. A good method for that is applicationDidFinishLaunching: in AppDelegate class:


- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:self];
}

And that's it! The message popup will be displayed together with the notification. I really recommend to check the documentation of classes that appered in this article. There are many other features like setting additional buttons or methods that are called when the notification is displayed or deliverd.

Hello, World!

Hi! I'm a software engineer, so I create software. A lot. Mostly for Macs and iPhones, so I'm using Cocoa and Cocoa Touch libraries every day. I also like to share my knowledge with other people. So I thought I should start a blog about Mac and iPhone software development. So I have.