iosswiftios13uiscreen

Ios 13 screen brightness problem by swift


I'm working on a project, and I have to control the screen brightness.

I use this to control:

UIScreen.main.brightness = CGFloat(0.80)

But, once I lock the screen and unlock, the screen brightness will change back to the system brightness, which could not go back to the brightness which I set before.

If there is any func I can use to change the screen brightness when users unlock the screen?

Thank you!


Solution

  • There is a method called applicationWillEnterForeground in UIApplicationDelegate which already conforms to your AppDelegate class. Implement applicationWillEnterForeground by typing name of this method inside your AppDelegate class. like:

    you can set the brightness whenever app goes to foreground

    class AppDelegate: UIResponder, UIApplicationDelegate {
    
      func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
          return true
      }
    
      func applicationWillEnterForeground(_ application: UIApplication) {
          UIScreen.main.brightness = CGFloat(0.80)
      }
    }