iOS: Impossible de définir UIApplication idleTimerDisabled YES dans didFinishLaunchingWithOptions

StackOverflow https://stackoverflow.com/questions/7355458

Question

J'ai une application iPad où l'utilisateur peut régler la idleTimerDisabled OUI ou NON via un commutateur dans les préférences. Cette partie fonctionne très bien. Cependant, il mise d'abord sur OUI dans la méthode du délégué de l'application de didFinishLaunchingWithOptions si elle est la première fois l'application a terme ne fonctionne pas (l'appareil automatique dort de toute façon).

J'ai essayé le hack de la mise à NO, puis YES, comme décrit dans d'autres threads en vain. Tous les autres aspects des préférences (standardUserDefaults) fonctionnent très bien, aussi bien.

Voici le code correspondant:

- (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;
    }
}
Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top