An example of how to keep the control screen bright and dark on IOS

Time:2021-4-13

preface

Recently, I’m doing a development. There’s a place to synchronize music files. Sometimes the screen will go out, resulting in the disconnection of synchronization. Now I decide to keep the screen always on during synchronization. In fact, many times we need to keep the screen bright. Now I’ll introduce an implementation method, but remember to turn off the screen at an appropriate time

Sample code

//Set screen always on
[UIApplication sharedApplication].idleTimerDisabled = YES;
//Cancel setting screen always on
[UIApplication sharedApplication].idleTimerDisabled = NO;
 
//Set screen always on
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
//Cancel setting screen always on
[[UIApplication sharedApplication] setIdleTimerDisabled:NO];

But some controls don’t lock the screen. For example, avplayer doesn’t lock the screen when playing, but after pausing or stopping playing, the system will automatically turn off the constant light, which conflicts with our design. So I made a monitor here. If the screen lock is turned off, turn it on immediately. Finally, remember to remove the monitor and turn off the lock.

//Monitor lock screen changes
[[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;
}

summary

The above is the whole content of this article, I hope the content of this article has a certain reference value for your study or work, if you have any questions, you can leave a message to exchange, thank you for your support for developer.