-1

How can I have a shell command run when a user clicks a Button in my Cocoa GUI?

I would like to have a button that when pressed, runs the command caffeinate to keep the computer awake.

I do not know how to code this function and have googled.

  • you may ask this question to google by adding more and more keywords to your search query like: macos run shell command objective C by the way check this out: https://stackoverflow.com/questions/412562/execute-a-terminal-command-from-a-cocoa-app – Alp Altunel Oct 26 '18 at 05:53
  • The Cocoa way is to create a [IOPMAssertion](https://developer.apple.com/documentation/iokit/1557134-iopmassertioncreatewithname?language=objc). The shell detour is not needed. – vadian Nov 05 '18 at 21:24

1 Answers1

0

You run command line commands via NSTask. You create an NSTask, set the path to the command you want to run, set up the arguments and then call the task. If you google how to use NSTask I'm sure you'll find some example code.

Here is the Apple Developer documentation for NSTask: https://developer.apple.com/documentation/foundation/nstask?language=occ

Dad
  • 6,388
  • 2
  • 28
  • 34
  • and I see that the comment you received pointing to another stack overflow answer has the code you need in detail. – Dad Nov 05 '18 at 21:19