I need to detect if the mac goes to sleep or does wake up.
I found:
Code: Select all
func applicationDidFinishLaunching(_ aNotification: Notification) {
NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(sleepListener(_:)),
name: NSWorkspace.willSleepNotification, object: nil)
NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(sleepListener(_:)),
name: NSWorkspace.didWakeNotification, object: nil)
}
@objc private func sleepListener(_ aNotification: Notification) {
print("listening to sleep")
if aNotification.name == NSWorkspace.willSleepNotification {
print("Going to sleep")
} else if aNotification.name == NSWorkspace.didWakeNotification {
print("Woke up")
} else {
print("Some other event other than the first two")
}
}
I tried something like this:
Code: Select all
Procedure Notification_SleepListenerCB(notification)
Protected notificationName = CocoaMessage(0, CocoaMessage(0, notification, "name"), "UTF8String")
Debug PeekS(notificationName, -1, #PB_UTF8)
Debug "Will sleep"
EndProcedure
app = CocoaMessage(0,0,"NSApplication sharedApplication")
Debug app
appDelegate = CocoaMessage(0, app, "delegate")
Debug appDelegate
delegateClass = object_getClass_(appDelegate)
Debug delegateClass
selector = sel_registerName_("willSleepNotification:")
Debug selector
notificationCenter = CocoaMessage(0, 0, "NSNotificationCenter defaultCenter")
class_addMethod_(delegateClass, selector, @Notification_SleepListenerCB, "v@:@")
CocoaMessage(0, notificationCenter, "addObserver:", appDelegate, "selector:", selector, "name:$", @"willSleepNotification", "object:", #nil)
i = 10
Repeat
Delay(1000)
Debug FormatDate("%yyyy.%mm.%dd %hh:%ii:%ss", Date())
i - 1
Until i = 0
Debug CocoaMessage(0, notificationCenter, "removeObserver:", appDelegate, "name:$", @"willSleepNotification", "object:", #nil)
I also don't now the structure of aNotification to detect the different notifications.
Ok I can also use 2 different callbacks, so this will not be my biggest problem.