swiftmacosnotificationsswift3nsusernotification

Creating interactive notifications for OS X


Mac Basics: Notifications keep you informed states that it's possible to create an interactive alert with an text input field:

For example, you can reply to a chat directly from a notification.

OS X chat alert

How can I implement it? For instance, I have a notification:

let notification = NSUserNotification.init()
notification.hasActionButton = true
notification.actionButtonTitle = "Agree"
notification.title = "Header"
notification.informativeText = "Text."

NSUserNotificationCenter.default.deliver(notification)

Solution

  • Banners, Alerts, and Badges are all types of NSUserNotification instances. The chat reply image is an example of a the alert style.

    To change the user NSUserNotification display style for your application, set the value for NSUserNotificationAlertStyle to alert in your application's Info.plist file. I should note that there are known issues and open radars with this in the Cocoa SDK. The default value for this is banner.

    You can then use the Display Information and Displayed Notification Buttons to customize the alert.

    See the NSUserNotification API reference for information on how you can customize the buttons, placeholder text, etc on the alert.

    Here's how I did it (Swift 2.2, if you are using Swift 2.3 or 3 your syntax may vary). The key is to set hasReplyButton to true.

    let notification = NSUserNotification()
    notification.hasActionButton = true
    notification.actionButtonTitle = "Agree"
    notification.title = "Title"
    notification.informativeText = "Text."
    notification.responsePlaceholder = "Placeholder"
    notification.hasReplyButton = true
    
    NSUserNotificationCenter.defaultUserNotificationCenter().deliverNotification(notification)
    

    Alert

    Alert with Reply