James Pierce
James Pierce

Reputation: 558

macOS Swift 3 - Handling notification alert action button

I'm new to Swift (but not to programming). I have simple app that provides an alert based on specific conditionals. I would like to execute a function (or even just set a variable) when one of the buttons is pressed. Ideally, I just need one button, but if for whatever reason, only the notification.actionButtonTitle can have a handler, that's fine with me.

My notification code is currently in a Swift file as a helper.

import Foundation

    class NotificationHelper {
      static func sampleNotification(notification: NSUserNotification) {
        let notificationCenter = NSUserNotificationCenter.default

        notification.identifier = "unique-id-123"
        notification.hasActionButton = true
        notification.otherButtonTitle = "Close"
        notification.actionButtonTitle = "Show"
        notification.title = "Hello"
        notification.subtitle = "How are you?"
        notification.informativeText = "This is a test"
        notificationCenter.deliver(notification)
      }
    }

Currently in AppDelegate, this is defined:

let notification = NSUserNotification()

…and I call the notification like this:

NotificationHelper.sampleNotification(notification: notification)

The resulting notification works, as you can see in the screenshot below. However, I cannot seem to listen to the button action. I have tried adding this to the AppDelegate as well as the NotificationHelper file, but I did not have any success with it:

func userNotificationCenter(center: NSUserNotificationCenter, didActivateNotification notification: NSUserNotification) {
  print("checking notification response")

}

Any idea of what I'm missing?

Thanks!

Sample macOS notification using Swift3

Upvotes: 3

Views: 1622

Answers (1)

Kane Cheshire
Kane Cheshire

Reputation: 1712

You'll need to assign something as the delegate of the NSUserNotificationCenter:

NSUserNotificationCenter.default.delegate = self

If you add this to your AppDelegate and make your AppDelegate conform to NSUserNotificationCenterDelegate:

class AppDelegate: NSObject, NSUserNotificationCenterDelegate {

}

Upvotes: 3

Related Questions