Swift-创建助手时发现的问题

标签 swift cocoa nsxpcconnection system-profiler

当我尝试为使用 system_profiler 命令检索系统软件和硬件详细信息的应用程序创建帮助程序时,出现以下错误。

Response from XPC service: HELLO XPC
Response from XPC service: /usr/sbin/system_profiler: /usr/sbin/system_profiler: cannot execute binary file"

代码如下。

class CommandHelper: NSObject,CommandHelperProtocol {
  func upperCaseString(_ string: String, withReply reply: @escaping (String) -> Void) {
    let response = string.uppercased()
    reply(response)
  }
  func loadServerURL(_ string: String, withReply reply: @escaping (String) -> Void) {
    let pipe = Pipe()
    let process = Process()
    process.launchPath = "/bin/sh"
    process.arguments = ["system_profiler","SPHardwareDataType"]
    process.standardOutput = pipe
    process.standardError = pipe
    let fileHandle = pipe.fileHandleForReading
    process.launch()
    let response = String(data: fileHandle.readDataToEndOfFile(), encoding: .utf8)

    print(response!)
    reply(response!)
  }
}

当我将 launchPath 设置为/usr/sbin/system_profiler 时,我得到空白输出。

最佳答案

Shell 执行脚本,而不是二进制文件。解决办法是直接运行该工具;几乎没有任何理由仅仅为了执行程序而启动 shell:

process.launchPath = "/usr/sbin/system_profiler"
process.arguments = ["SPHardwareDataType"]

此外,如果您不打算使用 stderr 管道,那么设置它是没有意义的:

/* process.standardError = pipe */

关于Swift-创建助手时发现的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53444585/

相关文章:

objective-c - NSWorkspace runningApplications 不返回我的 XPC mach 服务

macos - XPC 在工作区中的两个 cocoa 应用程序之间,NSXPCConnection 立即失效

objective-c - launchd 终止进程时是否调用了 XPC 中断处理程序?

ios - 来自 Apple Review Team 的 EXC_BREAKPOINT (SIGTRAP) 崩溃报告

ios - 传递 NSManagedObjectContext 的实例

xcode - 除我之外的所有 Mac 上均出现非法指令 4

Cocoa AsyncUDPSocket 框架,(长)标签变量解释和我的委托(delegate)有时会被调用

javascript - JS 中的 native OS X 应用程序?

ios - 如何使用 Swift 检查 UITableViewCell 完全可见/加载 - iOS (setSelected)

ios - AVPlayer 日志机制 - Swift