2

I am trying to control the brightness of the screen while the app is in the background, and I am not sure if this is possible.

this UIScreen brightness documentation notes that

Brightness changes made by an app remain in effect until the device is locked, regardless of whether the app is closed. The system brightness (which the user can set in Settings or Control Center) is restored the next time the display is turned on.

this does not seem to say that you cannot set the screen brightness while in the background, on the applications main thread or otherwise. It merely says that the brightness is reset on a lock/unlock cycle.

consider the below snippets:

backgroundTask = UIApplication.shared().beginBackgroundTask(withName: "something", expirationHandler: handler) // handler ends the background task
registerCallbackForSomeEvent(callback: changeScreenBrightness)

the event is irrelevant. I can print() while the app is suspended and it all works fine.

and the implementation of changeSCreenBrightness() is something like the following:

func changeScreenBrightness() {
    let newBrightness = getNewBrightnessSomehow()
    // main or global, it doesn't seem to be happening...
    DispatchQueue.main.async(execute: {
        // this works in the foreground?! but not the background..
        UIScreen.main().brightness = newBrightness
        // a print() will be executed however..
    })
}

so.. can anyone definitively say that this is impossible? or does someone have working code that I could study?

thanks!

johndo
  • 71
  • 5

2 Answers2

0

I have been trying to do something similar. I have tentatively conclude that this functionality is disabled when the App is not in foreground (although I am still searching for documentation to support this).

The user's original brightness IS however restored once the device is locked.

I would like to return the user to their original UI Brightness on minimise or quit. I am currently using the following code:

func _onApplicationLoad(){
    NotificationCenter.default.addObserver(self, selector: #selector(_onApplicationMinimise), name: Notification.Name.UIApplicationWillResignActive, object: nil)
}

func _onApplicationMinimise(){ // This function IS called on minimise
    // commands here run ok
    UIScreen.main.brightness = CGFloat(1.0) // this doesn't run
    // commands here run ok too
}
  • _onApplicationMinimise() function is called and works.
  • commands before the brightness line run.
  • commands after the brightness line run
  • UIScreen.main.brightness = 1.0 does NOT run
0

Please check my answer here: https://stackoverflow.com/a/57040935/2199288 You need to change that brightness in the AppDelegate

Trzy Gracje
  • 2,969
  • 4
  • 20
  • 24