You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NSUserNotificationCenter.default.deliver无法触发通知,求技术帮助

macOS命令行Swift程序无法弹出NSUserNotification的解决方案

问题根源

你的代码无法弹出通知主要有这几个原因:

  • 命令行程序没启动Cocoa应用的事件循环,NSUserNotification依赖完整的App运行环境
  • 没有把实现了代理的AppDelegate绑定到NSUserNotificationCenter
  • 命令行程序默认没有通知权限,必须主动请求授权

修复后的代码

import Foundation
import Cocoa

class AppDelegate: NSObject, NSApplicationDelegate {
    
    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // 绑定代理并请求通知权限
        NSUserNotificationCenter.default.delegate = self
        NSUserNotificationCenter.default.requestAuthorization(options: [.alert, .sound]) { granted, error in
            if granted {
                // 回到主线程发送通知
                DispatchQueue.main.async {
                    self.showNotification()
                }
            } else {
                print("通知权限未授予,请在系统设置中开启")
            }
        }
    }
    
    func showNotification() {
        let notification = NSUserNotification()
        notification.title = "Test of notification"
        notification.subtitle = "Subtitle of notifications"
        notification.informativeText = "Main informative text"
        notification.soundName = NSUserNotificationDefaultSoundName
        
        NSUserNotificationCenter.default.deliver(notification)
        
        // 发送通知后延迟3秒退出程序
        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
            NSApplication.shared.terminate(nil)
        }
    }
}

extension AppDelegate: NSUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: NSUserNotificationCenter, shouldPresent notification: NSUserNotification) -> Bool {
        return true
    }
}

// 初始化并启动Cocoa应用运行循环
let app = NSApplication.shared
let delegate = AppDelegate()
app.delegate = delegate
app.run()

运行说明

  1. 执行命令:swift a.swift
  2. 首次运行会弹出权限请求弹窗,点击「允许」
  3. 如果没看到权限弹窗,手动打开「系统偏好设置」→「通知」,找到对应的命令行程序(可能显示为swift),开启通知权限
  4. 通知弹出后,程序会在3秒后自动退出

额外提示

macOS 10.14及以上版本中,NSUserNotification已被标记为废弃,官方推荐使用UserNotifications框架来实现通知功能,如果你需要长期维护代码,可以考虑迁移到新框架。

内容的提问来源于stack exchange,提问作者kruztw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 09:20:27