Swift, macOS: Open terminal window at the location

Viewed 384

I'm trying to lunch terminal window and go to some local path in it:

my code:

public class func openShell(at url: URL?) {
    guard let url = url else { return }
    
    let shellProcess = Process();

    shellProcess.launchPath = url.path;

    //shellProcess.arguments = [
    //  "osascript -e 'tell application \"terminal\" to do script \"cd \(url)\"'"
    //];

    shellProcess.launch();
}

but as result there is some output into debug console inside of XCode but no shell window is opened.

commented code - alternative way that I have tried

2 Answers

2021, Swift 5.0

Answer is simple:

@available(OSX 10.15, *)
public class func openTerminal(at url: URL?){
    guard let url = url,
          let appUrl = NSWorkspace.shared.urlForApplication(withBundleIdentifier: "com.apple.Terminal")
    else { return }
    
    NSWorkspace.shared.open([url], withApplicationAt: appUrl, configuration: NSWorkspace.OpenConfiguration() )
}

on each func call will be opened the new instance of the Terminal with selected location.

And no need to make XPC service or turn off sandbox for this.

So basically you have two options here:

  1. you need to turn off sandbox to use this approach;
  2. you need to create XPC service and then call this stuff from there and it should work.

Second one is obviously better and in real application you should use this approach. Too learn more about XPC services you can check my repo where I do the same to parse processes info or check this guide and this

Related