Check if current screen is on or off in iOS

Viewed 3097

I know that it is possible to register an event listener when there is screen on/off event. What if I want to check whether currently the screen is on or off? Any method for me to check it?

If I use notification to check, here is the event that will happen:

When I lock the screen. It will trigger

--- received notification: com.apple.springboard.hasBlankedScreen --- received notification: com.apple.springboard.lockcomplete --- received notification: com.apple.springboard.lockstate --- received notification: com.apple.iokit.hid.displayStatus

When I unlock the screen, it will trigger

--- received notification: com.apple.springboard.hasBlankedScreen --- received notification: com.apple.springboard.lockstate --- received notification: com.apple.iokit.hid.displayStatus

I cannot simply detect lockcomplete to see if it is currently off, because it will also trigger lockstate and displaystatus when i tried to lock the screen.

3 Answers
private func displayStatusChanged(center: CFNotificationCenterRef?, observer: UnsafeMutableRawPointer?, name: CFString?, object: UnsafeRawPointer?, userInfo: CFDictionaryRef?) {
let nameCFString = name
let lockState = nameCFString as String
if let aName = name {
    print("Darwin notification NAME = \(aName)")
}
if (lockState == "com.apple.springboard.lockcomplete") {
    print("DEVICE LOCKED")
} else {
    print("LOCK STATUS CHANGED")
}
}  
func registerforDeviceLockNotification() {
  CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),  /*center */nil,  /* observer */displayStatusChanged,  /* callback */"com.apple.springboard.lockcomplete",  /* event name */nil,  /* object */CFNotificationSuspensionBehavior.deliverImmediately)
  CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),  /*center */nil,  /* observer */displayStatusChanged,  /* callback */"com.apple.springboard.lockstate",  /* event name */nil,  /* object */CFNotificationSuspensionBehavior.deliverImmediately)
 }
Related