Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift, macOS: Open terminal window at the location

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

like image 724
Andrew Avatar asked Nov 01 '25 12:11

Andrew


1 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.

like image 66
Andrew Avatar answered Nov 03 '25 08:11

Andrew