Using Process() to run Mac terminal commands in Apps


  • Share on Pinterest

Season 4 Episode 22

In this episode of the Compile Swift Podcast, I explain the problem and the solution for something I wanted to achieve and had to work to figure out.

I wanted to run Git commands in the app I built to create Markdown files for the Compile Swift Web site. It turned out to be a real educational discovery and opened my eyes to many possible uses.

Using Process() to run a terminal command turned out to be precisely what I needed. This is very helpful because I can also get the return from executing the command and use that in the app.

Here is the code sample that I talk about in the episode.

let process = Process()

process.executableURL = URL(fileURLWithPath: 
gitPath.absoluteString)  
process.currentDirectoryURL = URL(fileURLWithPath: 
savePath.absoluteString)  
process.arguments = ["add", fileName.path]  
let outPipe = Pipe()  
let outFile = outPipe.fileHandleForReading  
process.standardOutput = outPipe

do {  
  try process.run()  
  process.waitUntilExit()

  if #available(macOS 10.15.4, *) {  
  if  
  let data = try outFile.readToEnd(),  
  let returnValue = String(data: data, encoding: .utf8) {}
  gitCommit()  
} else {  
// Fallback on earlier versions  
}  
} catch {  
  print(error)  
}

Subscribe / Follow The Podcast

Click here to see all available platforms

Listen on Apple Podcasts
Listen on Spotify