Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to launch an external Process?

I am reading through the docs of swift and came across Type Methods. For example here: https://developer.apple.com/documentation/foundation/process

The offered Type Method is:

class func run(URL, arguments: [String], terminationHandler: ((Process) -> Void)? = nil)

How can I use this in my code? For example when I press a button? How can I add a clean-up function to the terminationHandler?

like image 229
doom4 Avatar asked Jan 19 '18 03:01

doom4


1 Answers

In a macos app, you may use run for launching external processes, an example might be:

1) one-shot execution:

let url = URL(fileURLWithPath:"/bin/ls")
do {
   try Process.run(url, arguments: []) { (process) in
      print("\ndidFinish: \(!process.isRunning)")
   }
} catch {}

2) you may want to use a Process instance to be able to setup more comfortably its behaviour, doing so:

let process = Process()
process.executableURL = URL(fileURLWithPath:"/bin/ls")
process.arguments = ["-la"]
process.terminationHandler = { (process) in
   print("\ndidFinish: \(!process.isRunning)")
}
do {
  try process.run()
} catch {}

So I did launch the ls command (you may check your console for the result), then in the closure terminationHandler I'm getting back such process.

like image 131
Andrea Mugnaini Avatar answered Oct 24 '22 05:10

Andrea Mugnaini