1

I've been trying to reset the user's default device brightness in the app delegate method: applicationDidEnterBackground by using this code:

UIScreen.mainScreen().brightness = screenBrightness!

The code gets called but the brightness is not reset. Anyone know how to get this working using Swift (not obj-c)

Tom Elliott
  • 1,908
  • 1
  • 19
  • 39
Charlie S
  • 4,366
  • 6
  • 59
  • 97

2 Answers2

1

This code looks correct, but note that it will not work in the simulator, it will only take effect on a physical device.

Also, ensure that the value of screenBrightness is between 0 and 1.

You will likely not be able to change the screen brightness while in the background. From Apple's documentation:

Brightness changes made by an app remain in effect only while the app is active. The system restores the user-supplied brightness setting at appropriate times when your app is not in the foreground.

Tom Elliott
  • 1,908
  • 1
  • 19
  • 39
  • Yeah. Trying this on a real device (iPhone 6) with brightness set to 0.5. Seems to work ok when setting in UIViewControllers, but not working in the AppDelegate when the app is backgrounded. – Charlie S Aug 31 '15 at 10:08
  • Just updated my answer, unfortunately, you won't be able to change the brightness while in the background. – Tom Elliott Aug 31 '15 at 12:41
  • Hi Tom. Im actually trying to set it just before it gets backgrounded (tried both: applicationDidEnterBackground & applicationWillResignActive).. but guess that might be too late? – Charlie S Sep 01 '15 at 08:55
  • Regardless, once your app goes into the background, the brightness setting will be reset, and the brightness you set within the app will not be remembered. Can you describe exactly what you're expecting to see? – Tom Elliott Sep 01 '15 at 12:34
  • Yeah - that is the problem I am having. If the user's brightness is 0.5 when they open my app and then my app changes it to 1.0. When the user closes the app it remains at 1.0 (rather than 0.5). So trying to take note of 0.5 myself and then update it myself just before the app closes. – Charlie S Sep 01 '15 at 18:44
  • Ah, that's odd. Totally counter to the documentation, sounds like a bug. Not sure how you might work around this, perhaps you could try making a call in a `viewWillDisappear` method if you don't have many views. – Tom Elliott Sep 01 '15 at 19:34
-1

You need to change the brightness in the AppDelegate. For some reason it doesn't work properly when triggered in a view controller from a notification (willResignActiveNotification, didEnterBackgroundNotification, willTerminateNotification). Although, you can use AppDelegate methods for that:

func applicationWillResignActive(_ application: UIApplication) {
    UIScreen.main.brightness = 0.5
}
Trzy Gracje
  • 2,969
  • 4
  • 20
  • 24