User Notifications notify the user that something has changed in the application. Best known examples are the upcoming events in Calendar or the build status in Xcode.
Notification Center provides an overview of notifications from applications. As we will see, it’s very easy to integrate and display basic notifications in it.
Three display styles are available: None, Banner and Alert. By default, User Notifications are displayed using the Banner style.
We use two objects:
NSUserNotification: to create and manage the notification
NSUserNotificationCenter: to display the notification
However this piece of code does not really display the notification, the Notification Center decides if it should be displayed or not. Usually, the notification it’s not display if the app is already in focus.
To do that, we need to implement NSUserNotificationCenterDelegate protocol. AppDelegate’s applicationDidFinishLaunching method is a good candidate. You can force a notification to be displayed, thanks to userNotificationCenter:shouldPresent.
Banners are simple notification view, dismissed after a few seconds.
On the contrary of banners, alerts aren’t dismissed automatically.
To modify the notification style we need to add a property into Info.plist. Set NSUserNotificationAlertStyle as key with alert string value.
Adding an action
We can add a reply field with a custom placeholder.
After the user validated his response, the Notification Center will call userNotificationCenter:didActivate, we just need to check the activation type:
By default, on alert you’ll have default buttons, like displayed before. We can configure them, to match what you want.
It’s sometimes useful to offer multiple actions to users, directly from the notification, as a non-breaking workflow.
Additional actions are an array of NSUserNotificationAction:
Currently, you need to hold-click the action button to display the additional actions and there is no little arrow on hover.
Go back to userNotificationCenter:didActivateNotification and add these switch cases:
Finally, let’s say we want to schedule the display to be 10 seconds later and then to repeat it every day.
Notice, that instead of deliver, we used schedule function.