devinshine
devinshine

Reputation: 61

How to execute a unix executable file with Swift

I developing a OS X application with swift. I need to use some library on my application. The library is a Unix executable file. I can execute the Unix executable file on terminal.

This is example:

pngquant --quality=65-80 test.png

But I need execute the Unix executable file on OS X application. I don't know how to do it.

I think should execute command on OS X application, and find an awesome library to execute the command.

Using swiftline example:

let result = run("ls -all")
print(result.stdout)

Print content:

total 0
drwxr-xr-x  6 DevinShine  staff  204 Dec 23 22:18 .
drwxr-xr-x@ 3 DevinShine  staff  102 Dec 23 22:16 ..
drwxr-xr-x  3 DevinShine  staff  102 Dec 23 23:25 Pion.app
drwxr-xr-x  4 DevinShine  staff  136 Dec 23 22:18 Pion.swiftmodule
drwxr-xr-x  7 DevinShine  staff  238 Dec 23 22:18 Pods.framework
drwxr-xr-x  7 DevinShine  staff  238 Dec 23 22:18 Swiftline.framework

I copy Unix executable file to Build Phases.

look picture

But I don't know how to move Unix executable file to OS X application and execute it.

Please help me,thx.

Upvotes: 2

Views: 3660

Answers (1)

devinshine
devinshine

Reputation: 61

I resolved it. The way is easy.

I run my application and execute run("pwd")

let result = run("pwd")
print(result.stdout)
let fullPath = result.stdout + "/Pion.app/Contents/MacOS/pngquant"

print content:

/Users/apple/Library/Developer/Xcode/DerivedData/Pion-ebbvaypzstbbordxhgeutzopihtt/Build/Products/Debug

excute pngquant function:

run(fullPath + " /Users/apple/Documents/test.png")

Update at 2015-12-25

NSBundle.mainBundle().executablePath will give you the path to your .app wrapper, so code is very clear.

run(NSBundle.mainBundle().executablePath + "pngquant /Users/apple/Documents/test.png")

Upvotes: 3

Related Questions