Created
June 26, 2020 07:36
-
-
Save koingdev/191fa22bd7a40bffbdddacda1f3b9d30 to your computer and use it in GitHub Desktop.
Simple Swift Brightness Manager class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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