SoFunction
Updated on 2025-04-09

Example of iOS method to control the screen to keep light and dark

Preface

Recently, I was working on a development where there is a place to synchronize music files. The screen will be off when there is time, which will cause the synchronization to be disconnected. Now I have decided to keep the screen always bright during synchronization. In fact, we need to keep the screen brighter. Let me introduce a method to you below, but remember to turn off the constant light at the appropriate time.

Sample code

//Set the screen always light[UIApplication sharedApplication].idleTimerDisabled = YES;
//Cancel the screen always lights[UIApplication sharedApplication].idleTimerDisabled = NO;
 
//Set the screen always light[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
//Cancel the screen always lights[[UIApplication sharedApplication] setIdleTimerDisabled:NO];

However, some controls do not lock the screen. For example, AVPlayer does not lock the screen during playback, but after pausing or stopping the playback, the system will automatically turn off and keep on lit, which is exactly in conflict with our design. So I did a monitoring here. If the screen lock screen is turned off, turn it on immediately. Finally, remember to remove the monitoring and turn off the lock screen.

// Monitor the change of lock screen[[UIApplication sharedApplication] addObserver:self forKeyPath:@"idleTimerDisabled" options:NSKeyValueObservingOptionNew context:nil];
 
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
 // setToast(@"value change operation"); if (![UIApplication sharedApplication].idleTimerDisabled) {
 [UIApplication sharedApplication].idleTimerDisabled = YES;
 }
}
 
 
- (void)dealloc{
 [[UIApplication sharedApplication] removeObserver:self forKeyPath:@"idleTimerDisabled"];
 [UIApplication sharedApplication].idleTimerDisabled = NO;
}

Summarize

The above is the entire content of this article. I hope that the content of this article has a certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.