iOS:无法在 didFinishLaunchingWithOptions 中将 UIApplicationidleTimerDisabled 设置为 YES

发布于 2024-12-03 10:23:04 字数 764 浏览 3 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心碎的声音 2024-12-10 10:23:04

使用 registerDefaults 方法NSUserDefaults 而不是测试 objectForKey 是否为零。

另请参阅 有关编程指南的详细信息。一旦您使用 registerDefaults 注册了默认值(在您的情况下,您的 "autoSleep" 键的值为 NO),您就可以确保此键中有一个值,要么是用户在应用程序设置中设置的值……要么是默认值(如果用户尚未为其设置值)。

因此,它应该可以解决您的问题,因为您的 autoSleep 键始终会有一个值,可以是默认值,也可以是用户提供的值。

Use the registerDefaults method of NSUserDefaults 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文