Swift-创建助手时发现的问题
Swift-Problem discovered when creating a helper
当我尝试为使用 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 */
当我尝试为使用 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 */