[英]Not receiving DistributedNotificationCenter in Swift Command Line Tool
我正在 node.js 中构建一个小应用程序,它使用execa
读取来自已编译 Swift 应用程序的打印语句。 这个想法类似于 Sindre Sorhus(还有谁!?)请勿打扰
虽然我不是 Swift 程序员,但我整理了一个非常简单的解决方案。 二进制文件是通过从 CL 运行swift build --configuration=release
来编译的,以便在节点应用程序中使用。 它还可以在 XCode 的 Swift 游乐场中很好地编译(没有 CLI 部分),我可以看到正确的打印语句。
import Cocoa
var isLocked:Bool = false
DistributedNotificationCenter.default().addObserver(forName: .init("com.apple.isScreenLocked"), object: nil, queue: nil) { notification in
print("Screen is locked")
isLocked = true
}
DistributedNotificationCenter.default().addObserver(forName: .init("com.apple.isScreenUnlocked"), object: nil, queue: nil) { notification in
print("Screen is unlocked")
isLocked = false
}
struct CLI {
static var standardInput = FileHandle.standardInput
static var standardOutput = FileHandle.standardOutput
static var standardError = FileHandle.standardError
static let arguments = Array(CommandLine.arguments.dropFirst(1))
}
switch CLI.arguments.first {
case "status":
print(isLocked)
default:
print("Unsupported command", to: .standardError)
exit(1)
}
// Some other functions omitted for brevity
现在,当我从 Node.js 运行下面的代码时,一切似乎都运行良好。 但是由于某种原因,观察者没有收到通知。
'use strict';
const execa = require('execa');
const electronUtil = require('electron-util/node');
const binary = path.join(electronUtil.fixPathForAsarUnpack(__dirname), 'IsLockedOrNot');
setInterval(async () => {
const {stdout} = await execa(binary, ['status']);
console.log(stdout) // keeps logging false, also when screen is locked
}, 1000)
有谁知道为什么在这种情况下没有收到通知? 我尝试了各种方法,例如明确禁用睡眠模式shell.exec('sudo pmset -a disablesleep 1')
并使用--disable-sandbox
标志编译应用程序。 没有运气,直到知道..
使用基础 child_process 库而不是 execa 中的 spawn,确保您遵循 stdout,对于 nodejs 和 swift 最重要的部分是在每一行之后刷新缓冲区。 否则,您必须等待程序结束才能收到任何输出。 在每次需要“换行符”的“打印”之后使用“import Darwin.C”和“fflush(stdout)”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.