8

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?

mugx
  • 9,869
  • 3
  • 43
  • 55
doom4
  • 633
  • 5
  • 19

1 Answers1

18

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.

mugx
  • 9,869
  • 3
  • 43
  • 55
  • 1
    Awesome thanks. Quick follow up. If I declare everything by hand like `let process = Process ()` and then want to use the terminational handler by invoking `var terminationHandler: ((Process) -> Void)?` how would the syntax look like for this closure? Is it even a closure? I am new to swift and all is still confusing. – doom4 Jan 19 '18 at 04:17
  • 1
    You are welcome. I added an edit related to your question. – mugx Jan 19 '18 at 04:25
  • I get "createProcess: runInteractiveProcess: exec: permission denied (Operation not permitted)", which entitlement do I need to set to give permission for my app? – psksvp Jan 21 '20 at 11:01