macOS Swift应用本地通知无法正常显示问题排查
问题分析与解决方案
核心问题:混用了新旧通知框架
你当前代码同时使用了两套不兼容的macOS通知API:
- 权限请求用的是现代UserNotifications框架(
UNUserNotificationCenter) - 发送通知却用的是已废弃的NSUserNotification框架(
NSUserNotificationCenter)
这两套框架的权限是独立管理的,即便你通过UNUserNotificationCenter获取了权限,NSUserNotificationCenter依然没有权限,直接导致通知无法显示。
修复步骤
1. 统一使用现代UserNotifications框架
完全弃用NSUserNotification和NSUserNotificationCenter相关代码,改用现代API实现通知逻辑。
权限请求代码(可保留,但要确保后续逻辑匹配)
let center = UNUserNotificationCenter.current() center.requestAuthorization(options: [.alert, .sound, .badge, .provisional]) { allowed, error in if allowed { print("Notifications allowed") } else { print("Notifications denied") } }
替换发送通知的代码
将原NSUserNotification相关代码替换为:
// 构建通知内容 let content = UNMutableNotificationContent() content.title = "test" content.subtitle = "Test notification" content.body = "this the test notification" content.sound = UNNotificationSound.default // 创建通知请求(需唯一标识符) let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil) // 发送通知 UNUserNotificationCenter.current().add(request) { error in if let error = error { print("发送通知失败: \(error.localizedDescription)") } }
2. 配置现代通知框架的代理
如果需要应用在前台时也显示通知横幅,需设置UNUserNotificationCenter的代理并实现对应方法:
更新你的AppDelegate:
class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { // 设置现代通知框架代理 UNUserNotificationCenter.current().delegate = self } // 允许应用前台时显示通知横幅 func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions { return [.banner, .sound, .badge] } }
3. 额外检查项
- 确认系统通知设置:进入「系统设置→通知→你的应用」,确保“允许通知”已开启,横幅样式配置正确。
- 若使用
provisional临时权限,需注意该权限仅在macOS 10.14+生效,且临时通知不会留存到通知中心,仅显示横幅。 - 清理Xcode缓存后重新构建运行,避免旧代码残留影响。
内容的提问来源于stack exchange,提问作者Abdul Sami Sultan
相关产品推荐
相关产品推荐

