swiftcocoansxpcconnectionsystem-profiler

Swift-Problem discovered when creating a helper


When i try to create a helper for an application that retrieve system software and hardware details using system_profiler command i got the following error.

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

The code is given below.

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!)
  }
}

When i set launchPath to /usr/sbin/system_profiler i got blank output.


Solution

  • Shells execute scripts, not binaries. The solution is to run the tool directly; there's hardly any reason to launch a shell just to execute a program:

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

    Also, there's no point in setting the stderr pipe if you're not going to use it:

    /* process.standardError = pipe */