0

I'm looking for a function which will get called when a macOS machine wakes up from sleep.

What are some ways to achieve this?

I'm looking to run code in my Swift application when the computer awakens. I'm trying to open a new websocket when this happens. If I open the lid -> new websocket, if I press the any key -> new websocket.

What I've found useful so far is this which stems from what @Rob Napier has suggested (didWakeNotification)

jscs
  • 63,694
  • 13
  • 151
  • 195
OrangePot
  • 1,053
  • 2
  • 14
  • 38
  • 1
    What kind of machine? – jscs Oct 25 '17 at 22:41
  • Has to work for any machine, OS 10.10+ – OrangePot Oct 25 '17 at 22:44
  • @JoshCaswell I'm not sure if these edits match the OP's original intent; it feels like a different question now. Is this what you meant, @OrangePot? – Rob Napier Oct 25 '17 at 23:50
  • I basically just added the fact that we're talking about a Mac and cleaned up the title, @RobNapier. I don't see how [my edit](https://stackoverflow.com/revisions/46943012/4) changed the meaning. – jscs Oct 26 '17 at 00:06
  • This isn't a Swift-specific question. You're asking about the operating system, or the system frameworks. – jscs Oct 26 '17 at 00:14

1 Answers1

3

You'll need to give more information than this. Is this an user-level (GUI?) application that will be running when the machine goes to sleep? Is this a daemon? Do you expect your program to be launched if it isn't already running? Is the program sandboxed? Do you expect to have root access? What if no one is logged in? "Wakes up from sleep" has many subtle corner cases (for example, it includes a "dark wake" mode which are not quite sleep and not quite wake).

That said, the high-level answer is "observe NSWorkspace.didWakeNotification" and the low-level answer is "call IORegisterForSystemPower." But whether either of those help you depends a lot on what problem you're solving.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610