SwiftUI:如何使用 MacOS 应用程序访问终端?

SwiftUI: How to access terminal with MacOS app?

所以我有这个按钮,可以让我在终端中 运行 /usr/bin/say,效果很好。但是当我尝试更改 executableURL 变量时,我 运行 sudo nano /private/etc/hosts 相反,我收到此错误 所以我的问题是,如何通过我的 macOS 应用程序和 运行 sudo nano /private/etc/hosts?

访问终端
 Button(action: {
          let executableURL = URL(fileURLWithPath: "/usr/bin/say")
    //    let executableURL = URL(fileURLWithPath: "sudo nano /private/etc/hosts")
    
           self.isRunning = true
           do {
               try Process.run(executableURL,
                               arguments: ["Hello World"],
                               terminationHandler: { _ in self.isRunning = false })
               } catch{
                     print(error)
               }
                    
            }) {
                Text("Say")
            }

编辑:

通过使用这个参数 arguments: ["-c", "echo myPassword | sudo -S -- sh -c \"echo \"127.0.0.1www.apple.com \" >> /etc/hosts\""] 行和此路径 URL(fileURLWithPath: "/bin/zsh") 我能够附加到主机文件。

我遇到的一个问题是,我能够附加您在图片中看到的内容(不是第 1 行),但由于某种原因,当我尝试像以前一样执行相同操作时,不再附加任何内容。这是个大问题。我想我必须在添加一些内容后创建一个新行。关于如何做到这一点有什么想法吗?

尝试禁用应用沙盒。那应该可以了。

编辑:

    let executableURL = URL(fileURLWithPath: "/bin/zsh")

    self.isRunning = true
    do {
        try Process.run(executableURL,
                        // Replace userpassword with the user's password and yourline with the line you want to append to the file. (If you really want to use nano, you can replace echo... >> ... with nano /private/etc/hosts)
                        arguments: ["-c", "echo password | sudo -S -- sh -c \"echo test >> /etc/hosts\""],
                        terminationHandler: { _ in self.isRunning = false })
    } catch {
        print(error)
    }