iOS:无法在 didFinishLaunchingWithOptions 中将 UIApplicationidleTimerDisabled 设置为 YES
我有一个 iPad 应用程序,用户可以通过首选项中的开关将idleTimerDisabled 设置为“是”或“否”。那部分工作正常。但是,如果应用程序第一次运行,则最初在应用程序委托的 didFinishLaunchingWithOptions 方法中将其设置为 YES 不起作用(设备会自动休眠)。
我尝试过先将其设置为“否”,然后设置为“是”,如其他线程中所述,但无济于事。首选项(standardUserDefaults)的所有其他方面也都工作正常。
这是相关代码:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// if app run for the first time, set these as defaults
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if (![prefs objectForKey:@"autoSleep"]) {
// this conditional code runs, as traced using NSLog
[prefs setBool:YES forKey:@"autoSleep"];
application.idleTimerDisabled = NO;
application.idleTimerDisabled = YES;
}
}
I have an iPad app where the user can set the idleTimerDisabled to YES or NO via a switch in preferences. That part works fine. However, initially setting it to YES in the app delegate's didFinishLaunchingWithOptions method if it's the first time the app has run doesn't work (the device auto-sleeps anyway).
I've tried the hack of setting it to NO first, then to YES, as described in other threads to no avail. All other aspects of the preferences (standardUserDefaults) are working fine, as well.
Here's the relevant code:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// if app run for the first time, set these as defaults
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if (![prefs objectForKey:@"autoSleep"]) {
// this conditional code runs, as traced using NSLog
[prefs setBool:YES forKey:@"autoSleep"];
application.idleTimerDisabled = NO;
application.idleTimerDisabled = YES;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
registerDefaults
方法NSUserDefaults
而不是测试 objectForKey 是否为零。另请参阅 有关编程指南的详细信息。一旦您使用 registerDefaults 注册了默认值(在您的情况下,您的
"autoSleep"
键的值为NO
),您就可以确保此键中有一个值,要么是用户在应用程序设置中设置的值……要么是默认值(如果用户尚未为其设置值)。因此,它应该可以解决您的问题,因为您的
autoSleep
键始终会有一个值,可以是默认值,也可以是用户提供的值。Use the
registerDefaults
method ofNSUserDefaults
instead of testing if objectForKey is nil.See also details about this in the relevant Programming Guide. Once you have register default values using registerDefaults (in your case the value
NO
for your"autoSleep"
key), you are ensured that you will have a value in this key, either the one set in the application's settings by the user… or this default one if the user hasn't set a value for it yet.Thus it should solve your problem as you will always have a value for your
autoSleep
key, either the default one or the user-provided one.