Search code examples
swiftxcodemacosappkit

Execute Pre-Compiled Bundled Program with Swift


I'm trying to build an app which uses a CLI tool for a lot of the work, and I'm wondering if it is possible to bundle and execute a pre-compiled tool from Swift in XCode on macOS 10.15+? I can add the binary to the bundle however the file is read-only and cannot be executed.

Example

There should be a binary called cli available in the bundle.

let stdOut = Pipe()
let process = Process()
process.executableURL = Bundle.main.url(forResource: "cli", withExtension: "")!
process.arguments = args
process.standardOutput = stdOut
try! process.run()

Error

Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=4 "The file “cli” doesn’t exist."

Solution

  • Yes, this is possible. The error you are seeing is most likely caused by the missing executable permission on the cli binary.

    Can you make sure the file is actually executable? You can just run ls -lh cli on the file. The output should look like this.

    ls -lh cli 
    -rwxr-xr-x@ 1 user  staff    36K 28 Mai 02:24 cli
    

    If your output is missing the x, then the file is missing executable permissions. You can add those to the file using chmod +x cli.