【发布时间】:2021-12-08 16:19:07
【问题描述】:
当我使用终止参数运行应用程序时(使用“Product”/“Scheme”/“Edit Scheme...”/“Run”/“Arguments”/“Argument Passes On Launch”设置),macOS 通知中心会出现一条通知并且应用程序终止。
#testapp application did finish launching
#testapp terminate mode enabled
#testapp terminating…
到目前为止,一切都很好......预期。
当我点击通知时,应用程序启动但userNotificationCenter 未触发(我在控制台应用程序中看不到#testapp notification triggered,但我看到以下内容)。
#testapp application did finish launching
#testapp terminating…
不正常吧?我该如何解决这个问题?
我开始认为这是 11.6 版中的 Big Sur 错误。
Big Sur 版本 11.4 (M1) 和 11.5 (Intel) 上一切正常。
感谢您的帮助!
//
// AppDelegate.swift
// Test
//
// Created by Sun Knudsen on 2021-10-22.
//
import Cocoa
import UserNotifications
@main
class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDelegate {
func showNotification(){
let content = UNMutableNotificationContent()
content.body = "Hello"
let request = UNNotificationRequest(
identifier: UUID().uuidString,
content: content,
trigger: nil
)
UNUserNotificationCenter.current().add(request)
}
func terminate() -> Void {
DispatchQueue.main.async {
NSApp.terminate(self)
}
}
func applicationDidFinishLaunching(_ notification: Notification) {
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (allowed, error) in
NSLog("#testapp application did finish launching")
if CommandLine.arguments.indices.contains(1) && CommandLine.arguments[1] == "terminate" {
NSLog("#testapp terminate mode enabled")
self.showNotification()
self.terminate()
} else {
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
self.terminate()
}
}
}
}
func applicationWillTerminate(_ aNotification: Notification) {
NSLog("#testapp terminating…")
}
func userNotificationCenter(
_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void
) {
NSLog("#testapp notification triggered")
self.terminate()
completionHandler()
}
}
在 GitHub 上https://github.com/sunknudsen/test-app 上提供测试应用程序。
【问题讨论】:
-
您需要向系统注册通知类别和通知动作。
-
@Mannopson 给定通知在应用程序运行时有效,这会在应用程序不运行时解决问题吗?
-
感谢@Willeke 的帮助。不知道如何发布示例,但整个应用程序只有约 150 行。请参阅github.com/sunknudsen/borg-wrapper/blob/master/Borg%20Wrapper/…。
-
TIL NSLog 消息显示在 Console.app 中(刚刚尝试过;确实如此)
标签: swift macos cocoa appkit apple-m1