谢天谢地,这个问题是 5 年前发布的,从那时起 Xcode 取得了长足的进步。
但是...这个错误在 2015 年仍然存在,并在使用 Xcode 6.2 和 iOS 8.2 时出现。
这是您实际需要做的,以防止您的设备进入睡眠状态。
(喝杯啤酒,这很痛苦。)
当我的应用第一次在设备上运行时,它会从网络服务加载一堆数据。但是,如果运行时间过长,屏幕会变暗,然后关闭,设备会锁定,并且我的 Web 请求会以丑陋的“网络连接丢失”错误而终止。
我尝试添加代码来简单地设置/取消设置idleTimerDisabled 值,但这种更改并没有持续很长时间,并且设备会在一段时间后自动锁定。
// This didn't work for me (for very long !)
[UIApplication sharedApplication].idleTimerDisabled = NO;
[UIApplication sharedApplication].idleTimerDisabled = YES;
相反,我需要做的(郁闷的叹息..)是每 20 秒设置/取消设置一个计时器。
在我的 .h 文件中:
@property (strong, nonatomic) NSTimer* stayAliveTimer;
-(void)callEveryTwentySeconds;
在我的 .m 文件中:
-(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];
}
真的吗,苹果?
现在是 2015 年,Xcode真的还这么糟糕...?
我希望这段代码可以帮助其他 Xcode 受害者。