首页 > 解决方案 > 无法在 macOS 上显示简单通知

问题描述

我对 Swift 有点陌生。我试图创建一个控制台应用程序/实用程序,在 macOS 上创建一个通知弹出窗口。如果没有,我似乎找不到任何方法。看起来这应该很简单,但我无法让通知弹出窗口显示:(

我在 macOS Sierra 上使用 swift 4.0.3

在最基本的层面上获得这项工作的任何指导将不胜感激!谢谢!

import Foundation
import Cocoa

let notification = NSUserNotification()
notification.title = "Title of notification"
notification.subtitle = "Subtitle of notification"
notification.soundName = NSUserNotificationDefaultSoundName
NSUserNotificationCenter.default.deliver(notification)

标签: swiftmacos

解决方案


仅当您的应用未获得焦点时才会发送通知。

如果你想交付它,你需要实现NSUserNotificationCenterDelegate一个协议和这些功能:

func userNotificationCenter(_ center: NSUserNotificationCenter, shouldPresent notification: NSUserNotification) -> Bool { return true }
private func userNotificationCenter(_ center: NSUserNotificationCenter, didActivate notification: NSUserNotification) -> Bool { return true }
public func userNotificationCenter(center: NSUserNotificationCenter, shouldPresentNotification notification: NSUserNotification) -> Bool { return true }

PS。我很确定,并非所有这些都需要 - 但我不知道哪些是


推荐阅读