How can we programmatically change the brightness of the iPhone screen?
17,791
Solution 1
[[UIScreen mainScreen] setBrightness: yourvalue];
Requires iOS 5.0 or later. yourvalue is a float between 0.0 and 1.0.
Solution 2
UPDATE: For Swift 3
UIScreen.main.brightness = YourBrightnessValue
Here's the swift answer to perform this
UIScreen.mainScreen().brightness = YourBrightnessValue
YourBrightnessValue is a float between 0.0
and 1.0
Solution 3
I had some problems with changing the screen brightness in viewDidLoad/viewWillDisappear so I created a singleton class to handle all the action. This is how I do it:
import Foundation
import UIKit
final class ScreenBrightnessHelper {
private var timer: Timer?
private var brightness: CGFloat?
private var isBrighteningScreen = false
private var isDarkeningScreen = false
private init() { }
static let shared = ScreenBrightnessHelper()
func brightenDisplay() {
resetTimer()
isBrighteningScreen = true
if #available(iOS 10.0, *), timer == nil {
brightness = UIScreen.main.brightness
timer = Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true) { (timer) in
UIScreen.main.brightness = UIScreen.main.brightness + 0.01
if UIScreen.main.brightness > 0.99 || !self.isBrighteningScreen {
self.resetTimer()
}
}
}
timer?.fire()
}
func darkenDisplay() {
resetTimer()
isDarkeningScreen = true
guard let brightness = brightness else {
return
}
if #available(iOS 10.0, *), timer == nil {
timer = Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true) { (timer) in
UIScreen.main.brightness = UIScreen.main.brightness - 0.01
if UIScreen.main.brightness < brightness || !self.isDarkeningScreen {
self.resetTimer()
self.brightness = nil
}
}
timer?.fire()
}
}
private func resetTimer() {
timer?.invalidate()
timer = nil
isBrighteningScreen = false
isDarkeningScreen = false
}
}
Author by
meetpd
I am the CEO of Upnexo Technologies Pvt. Ltd. We are a Product and Content Development Company. Our list of sites include: Upnexo.com HalfPantHippo.com TopVPN.Review SplitScreenApp.com ReviewRoller.com
Updated on June 15, 2022Comments
-
meetpd almost 2 years
How can I change the brightness of the screen programmatically using iPhone SDK?
-
Peter Sarnowski over 12 yearsGlad I could help. You can accept the answer if it is what you were looking for :)
-
Fernando Cervantes about 12 yearsWouldn't this get you kicked off the App Store though?
-
Peter Sarnowski almost 12 yearsIt's a perfectly legal API call. I can't see a reason why there should be any problem with it.
-
chengsam almost 8 years@Robse you may store the original brightness using
UIScreen.mainScreen().brightness
first then restore the brightness using this value at a later stage. -
Jared Chu over 7 yearsI add this line
[[UIScreen mainScreen] setBrightness: 0.6f];
toviewDidAppear
and nothing happened. -
oscar castellon over 6 yearsto request current brightness: let brillo : CGFloat = UIScreen.main.brightness