ios - 自动锁定 ios 设备,NSTimer 和 scheduledTimerWithTimeInterval

标签 ios nstimer auto-lock

我想在一定时间后触发操作(在生产中为 30 分钟),现在我正在使用 NSTimers scheduledTimerWithTimeInterval。在测试期间(超时为 20 秒,而不是 1800 秒),一切似乎都很好。在 Debug模式下(从 XCode 运行)一切似乎都很好,因为设备不会自动锁定。但在现实生活中,当应用程序在设备上运行时,自动锁定(准确地说是自动锁定,触发锁定按钮不会)“卡住”计时器(或至少将计时器触发器以某种方式移动到 future )。

我能处理这种情况吗?当然,我可以在 UIApplication sharedApplication 中禁用 idleTimer,但是当应用程序进入后台模式时,ipad 仍然可以自动锁定。

最佳答案

其实你可以,

首先,为 NSUserDefaults 创建“startTimeOfMyExoticTimer”的默认值:

[[[NSUserDefaults] standardDefaults] setObject:[NSDate date] forKey:@"startTimeOfMyExoticTimer"];

然后启动计时器检查有效时间范围是否结束:

[NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(checkIfTimeIsOver) userInfo:nil repeats:YES];

然后实现你的检查器方法:

-(void)checkIfTimeIsOver{
     NSDate * now = [NSDate date];
     NSDate * startTime = [[NSUserDefaults standardDefaults] objectForKey:@"startTimeOfMyExoticTimer"];

     // Here compare your now and startTime objects. (subsract them) and see the difference between them. If your time range is to be set on 30 seconds. Then you should check if the time difference between those objects are bigger than 30 seconds.

}

即使设备被锁定、应用程序处于后台等情况下,这也能正常工作。

这个方法对我有用,希望对你也有用

关于ios - 自动锁定 ios 设备,NSTimer 和 scheduledTimerWithTimeInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18400062/

相关文章:

iphone - 屏幕锁定时如何关闭我的 iPhone 应用程序?

ios - UILabel 设置为隐藏时不隐藏

ios - 是否有将属性字符串与本地化结合使用的方法?

ios - 使用 NSTimer 从服务器刷新数据

ios - 当应用程序处于后台时 NSTimer 的行为是什么?

ios - 无法通过 remotebuild 和 Visual Studio 2015 构建/调试 iOS Cordova 应用程序

ios - 在我的表格 View 底部添加一个工具栏

objective-c - NSTimer 变得更快

iphone - 在 iOS 4.3.3 的 iPhone 上禁用自动锁定