简体   繁体   中英

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

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

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.openFile("\(url.path)", withApplication: appUrl.path)
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM