For a recent MacOS project I had to hook into the system screen wake and sleep notifications. This is handled with the notification center in NSWorkspace.

let center = NSWorkspace.shared.notificationCenter;
let mainQueue = OperationQueue.main;

center.addObserver(forName: NSWorkspace.screensDidWakeNotification, object: nil, queue: mainQueue) { notification in
    screensChangedSleepState(notification)
}

center.addObserver(forName: NSWorkspace.screensDidSleepNotification, object: nil, queue: mainQueue) { notification in
    screensChangedSleepState(notification)
}

func screenChangedSleepState(_ notification: Notification) {
  switch(notification.name) {
  case NSWorkspace.screensDidSleepNotification:
      socket?.disconnect()
  case NSWorkspace.screensDidWakeNotification:
      self.openWebsocket()
  default:
      return
  }
}

There are two implementations of addObserver. The first takes a #selector argument and depends on an @objc callback. The second takes slightly different arguments, ending with a callback closure that does not depend on @objc.

Updated: