【问题标题】:macOS Swift 3 - Handling notification alert action buttonmacOS Swift 3 - 处理通知警报操作按钮
【发布时间】:2017-07-23 20:14:04
【问题描述】:

我是 Swift 新手(但不是编程新手)。我有一个简单的应用程序,它根据特定条件提供警报。当按下其中一个按钮时,我想执行一个函数(甚至只是设置一个变量)。理想情况下,我只需要一个按钮,但如果出于某种原因,只有 notification.actionButtonTitle 可以有一个处理程序,这对我来说很好。

我的通知代码目前作为助手位于 Swift 文件中。

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)
      }
    }

目前在AppDelegate,这是定义的:

let notification = NSUserNotification()

……我这样称呼通知:

NotificationHelper.sampleNotification(notification: notification)

生成的通知有效,如下面的屏幕截图所示。但是,我似乎听不到按钮动作。我已经尝试将它添加到 AppDelegate 以及 NotificationHelper 文件中,但我没有成功:

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

}

知道我缺少什么吗?

谢谢!

【问题讨论】:

    标签: swift macos


    【解决方案1】:

    您需要将某些内容指定为 delegateNSUserNotificationCenter

    NSUserNotificationCenter.default.delegate = self

    如果您将此添加到您的AppDelegate 并让您的AppDelegate 符合NSUserNotificationCenterDelegate

    class AppDelegate: NSObject, NSUserNotificationCenterDelegate {
    
    }
    

    【讨论】:

      猜你喜欢
      • 2014-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多