Why is the notification observer not triggering the selector function correctly when monitoring the iOS device's power mode status?

45 views Asked by At

Notification observer added to monitor the iOS device's power mode status(low power mode or not) is not triggering the selector function correctly.

I've added a notification observer to monitor the power mode status as follows:

NotificationCenter.default.addObserver(self, selector: #selector(handleSystemPowerStateChange), name: Notification.Name.NSProcessInfoPowerStateDidChange, object: nil)

The above line of code gets called in the viewDidLoad() of the View Controller

The code for the corresponding selector function is as follows:

    @objc func handleSystemPowerStateChange(_ notification: Notification) {
        
       if ProcessInfo.processInfo.isLowPowerModeEnabled {
            print("Low power mode enabled")
        } else {
            print("Low power mode disabled")
        }
    }

The expected behaviour is that whenever there is a change in the power mode(Low power to Normal / Normal to Low power mode), this function has to be called and the corresponding statement should be printed according to the power mode.

However this is not what happens. When I newly install a build, this function never gets called when the power mode changes. After I reinstall the build by making any minute code changes like adding an extra empty line before the NotificationCenter.default.addObserver(self, selector: #selector(handleSystemPowerStateChange), name: Notification.Name.NSProcessInfoPowerStateDidChange, object: nil) or re-adding the observer, it seems to work well(Clearly unexplainable behaviour).

Note: The app is in foreground.

How can I solve this? This does not seem to be an issue with the way in which the notification observer was added or the definition of the selector function.

0

There are 0 answers