Skip to content

Instantly share code, notes, and snippets.

@koingdev
Created June 26, 2020 07:36
Show Gist options
  • Save koingdev/191fa22bd7a40bffbdddacda1f3b9d30 to your computer and use it in GitHub Desktop.
Save koingdev/191fa22bd7a40bffbdddacda1f3b9d30 to your computer and use it in GitHub Desktop.
Simple Swift Brightness Manager class
final class Brightness {
// Config
private let maxBrightness: CGFloat
private(set) var defaultBrightness: CGFloat = 1.0
var isEnabled = true {
didSet {
if isEnabled {
setBrightnessToMax()
} else {
setBrightnessToDefault()
}
}
}
init(maxBrightness: CGFloat = 0.8) {
self.maxBrightness = maxBrightness
defaultBrightness = UIScreen.main.brightness
NotificationCenter.default.addObserver(forName: NSNotification.Name.UIApplicationWillResignActive, object: nil, queue: .main) { [weak self] _ in
guard let s = self else { return }
if s.isEnabled {
s.setBrightnessToDefault()
}
}
NotificationCenter.default.addObserver(forName: NSNotification.Name.UIApplicationDidBecomeActive, object: nil, queue: .main) { [weak self] _ in
guard let s = self else { return }
s.defaultBrightness = UIScreen.main.brightness
if s.isEnabled {
s.setBrightnessToMax()
}
}
}
private func setBrightness(toValue value: CGFloat) {
Queue.main {
UIScreen.main.brightness = value
}
}
private func setBrightnessToMax() {
setBrightness(toValue: maxBrightness)
}
private func setBrightnessToDefault() {
setBrightness(toValue: defaultBrightness)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment