SwiftUI: How to access terminal with MacOS app?

Viewed 367

So I have this button that lets me run /usr/bin/say in the terminal, which works just fine. But when I try to change the executableURL variable, so I run sudo nano /private/etc/hosts instead, I get this error enter image description here So my question is, how can I access the terminal through my macOS app and run 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")
            }

EDIT:

By using this arguments arguments: ["-c", "echo myPassword | sudo -S -- sh -c \"echo \"127.0.0.1www.apple.com \" >> /etc/hosts\""] line and this path URL(fileURLWithPath: "/bin/zsh") I was able to append to the hosts file.

A problem that I'm having is that I was able to append the things you see in the picture(not line 1) but for some reason nothing is appended anymore when I try to do the same as before. Which is a big problem. I think I have to create a new line after appending something. Any ideas on how to do this?

enter image description here

1 Answers

Try disabling the App Sandbox. It should work then.

EDIT:

    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)
    }
Related