iOS中设置禁止自动锁屏无效的解决方案

一般情况下,在代码中设置

1
[UIApplication sharedApplication].idleTimerDisabled = NO;

这样可以禁止自动锁屏

然而从iOS 3 直到iOS10,禁止自动锁屏概率性失效的BUG苹果一直未修复

使用以下代码可完全禁止自动锁屏

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
-(void)callEveryTwentySeconds
{
// DON'T let the device go to sleep during our sync
[[UIApplication sharedApplication] setIdleTimerDisabled:NO];
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
}

-(void)loadDataFromWebService
{
self.stayAliveTimer = [NSTimer scheduledTimerWithTimeInterval:20.0
target:self
selector:@selector(callEveryTwentySeconds)
userInfo:nil
repeats:YES];

//
// Code to call our web service in a background thread and wait
// for it to finish (which might take a few minutes)
//

// Kill off our "Stay alive" timer, and allow the device to Auto Lock whenever it wants.
[self.stayAliveTimer invalidate];

// Give our device permission to Auto-Lock when it wants to again.
[[UIApplication sharedApplication] setIdleTimerDisabled:NO];
}