代碼設置屏幕常亮:
[[UIApplication sharedApplication] setIdleTimerDisabled: YES];
一句代碼搞定!
補充:
APP某個版本上線后有司機反饋應用升級后如果不操作APP,屏幕不久就會息屏。對于司機來說在行駛過程中黑屏或者駕駛中操作手機都是一種危險行為,而技術人員也沒辦法通知所有的用戶在設置-顯示與亮度-自動鎖定
選擇永不
,所以直接在代碼層面解決該問題才是王道(被動等待司機反饋,不如主動出擊)。
經網上查詢得知在調用系統拍照結束時系統會將idleTimerDisabled
屬性設置為NO
(也有文章介紹在使用AVPlayer播放結束后該屬性也會被設置為NO
,然而經過在iOS13.3系統的iPhone XS Max上測試發現屬性值并未改變)。受此啟發,可能新版本中某功能也會存在類似設置。
解決方法:監聽idleTimerDisabled
屬性,當值被設置為NO
時,將idleTimerDisabled
屬性值修改為YES
。同時不要忘記在合適的地方移除監聽。
代碼如下:
- (void)keepIdleTimerDisabled {
[[UIApplication sharedApplication] setIdleTimerDisabled: YES];
[[UIApplication sharedApplication] addObserver:self forKeyPath:@"idleTimerDisabled" options:NSKeyValueObservingOptionNew context:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
if (![UIApplication sharedApplication].idleTimerDisabled) {
[UIApplication sharedApplication].idleTimerDisabled = YES;
}
}
- (void)dealloc{
[[UIApplication sharedApplication] removeObserver:self forKeyPath:@"idleTimerDisabled"];
[UIApplication sharedApplication].idleTimerDisabled = NO;
}