Swift命令行工具未收到DistributedNotificationCenter通知

问题描述 投票:0回答:1

[我正在尝试创建一个非常基本的Swift命令行应用程序,当macOS UI更改为明/暗模式时,使用WebSocket向另一个应用程序发出信号。

由于某种原因,命令行工具没有从DistributedNotificationCenter,特别是AppleInterfaceThemeChangedNotification接收any通知。但是,在applicationDidFinishLaunching上的Cocoa UI应用中运行完全相同的代码可以很好地工作。

我发现了一个old Obj-C CLI project on Github,它打算打印出所有通知,但也没有任何作用。这让我怀疑苹果也许已经改变了某些东西,但是我似乎无法在网上找到任何关于它的东西。我需要设置某些Xcode项目设置吗?

// main.swift

import Foundation

class DarkModeObserver {

    func observe() {
        print("Observing")
        DistributedNotificationCenter.default.addObserver(
            forName: Notification.Name("AppleInterfaceThemeChangedNotification"),
            object: nil,
            queue: nil,
            using: self.interfaceModeChanged(notification:)
        )
    }

    func interfaceModeChanged(notification: Notification) {
      print("Notification", notification)
    }

}

let observer = DarkModeObserver.init()
observer.observe()


RunLoop.main.run()
swift macos command-line-interface nsnotificationcenter macos-darkmode
1个回答
0
投票

我设法使iTunes通知正常运行,因此只是主题更改通知不起作用。鉴于此,我怀疑Apple仅将通知发送到UI / NSApplication应用程序。因此,请使用以下方法替换上方的最后3行:

let app = NSApplication.shared

class AppDelegate: NSObject, NSApplicationDelegate {

    func applicationDidFinishLaunching(_ notification: Notification) {
        let observer = DarkModeObserver.init()
        observer.observe()
    }

}

let delegate = AppDelegate()
app.delegate = delegate
app.run()
© www.soinside.com 2019 - 2024. All rights reserved.