Scheduled notifications in macOS

Notifications are a very useful addition to macOS applications, when done right can help inmensly. 

Here’s how you create scheduled and immediate notifications. Let’s start with the immediate ones:

func triggerNotification() -> Void {

    let notification = NSUserNotification()

    notification.title = “titleOfNotification”

    notification.informativeText = “whateverTextYou WantToAdd”

    notification.soundName = NSUserNotificationDefaultSoundName

    NSUserNotificationCenter.defaultUserNotificationCenter().deliverNotification(notification)

}

This will trigger a notification the moment you execute it, if however you would like to schedule a notification for a later date you can do:

func showNotification(atDate: NSDate) -> Void {

    let notification = NSUserNotification()

    notification.title = “It’s MONTH”

    notification.informativeText = “Time to check your finances!”

    notification.soundName = NSUserNotificationDefaultSoundName

    notification.deliveryDate = NSDate().dateByAddingTimeInterval(5.0)

    //notification.deliveryDate = getDateOfNextNotification()

    NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification(notification)

}

In this case you would be showing the notification after 5 seconds, more useful though is to plan it for a later date, like you can see in my commented code. The getDateOfNextNotification function simply returns the NSDate where I would like the notification to trigger. 

If you plan to use this, for instance in App Delegate, you may want to check if you have already scheduled notification to avoid duplicates. You can do the following:

func scheduleUpcomingAlertNotification() -> Void {

    let pipeOfNotifications = NSUserNotificationCenter.defaultUserNotificationCenter().scheduledNotifications.count

    if( pipeOfNotifications > 0){

        return

    }else trigger the function

Questions / comments? I’m at @MarcMasVi 

Marc