iOS超时功能无法正常工作

时间:2011-12-03 03:29:55

标签: objective-c ios cocoa-touch timeout

我在我的应用中添加了此代码作为自动超时。 userDefaults doubleForKey:@"timeoutLength"应该在几分钟内。例如,如果值为500,那应该意味着500分钟。

即使它真的不是500 + min,我仍然看起来正在打出一个小小的循环。我的代码有什么问题吗?也许是一分钟/秒的错误等。

    [userDefaults setDouble:[[userContextDictionary valueForKey:@"autologout_idle_timeout"] doubleValue] forKey:@"timeoutLength"];


    double timeDifference = ([[NSDate date] timeIntervalSince1970] - [userDefaults doubleForKey:@"Close Time"]) / 60;

    if (timeDifference > [userDefaults doubleForKey:@"timeoutLength"]) {
        NSLog(@"Timeout Hit");
    } else {
        NSLog(@"No Timeout");
    }

编辑:

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [userDefaults setObject:[NSDate date]  forKey:@"Close Time"];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {   
    [userDefaults setDouble:[[userContextDictionary valueForKey:@"autologout_idle_timeout"] doubleValue] forKey:@"timeoutLength"];  
    //This is an int like 500, or 600, etc. 

    NSDate *closeDate = [userDefaults objectForKey:@"Close Time"]
    NSTimeInterval timeWhenClosedTimeInterval = [closeDate timeIntervalSince1970];
    NSTimeInterval todayTimeInterval = [[NSDate date] timeIntervalSince1970];

    NSTimeInterval timeDifference = ((todayTimeInterval - timeWhenClosedTimeInterval ) / 60);
    if (timeDifference > [userDefaults doubleForKey:@"timeoutLength"]) {
        NSLog(@"Timeout Hit");
    } else {
        NSLog(@"No Timeout");
    }
    return YES;
}

2 个答案:

答案 0 :(得分:1)

我的猜测是设置NSUserDefaults值时出错,或者timeDifference计算出错。添加此行并确保实际将超时长度设置为500:

NSLog(@"Timeout length: %f, close time: %f, time difference: %f", [userDefaults doubleForKey:@"timeoutLength"], [userDefaults doubleForKey:@"Close Time"], timeDifference);

答案 1 :(得分:1)

NSTimeInterval以表示,而不是分钟。

Here's the Apple doc where it's described

我不是百分之百确定你的最终问题,但500秒似乎没有足够的时间。

与此同时,我为您自己的代码编写了一些更改代码:

NSDate * yesterday = [[NSDate date] dateByAddingTimeInterval: (-1 * 60 * 60 * 24 )];
NSTimeInterval yesterdayTimeInterval = [yesterday timeIntervalSince1970];
NSTimeInterval todayTimeInterval = [[NSDate date] timeIntervalSince1970];

// this properly converts timeDifference in seconds to minutes
NSTimeInterval timeDifference = ((todayTimeInterval - yesterdayTimeInterval ) / 60);
NSLog( @"time difference is %4.2f", timeDifference );

得出1400分钟(除以每小时60分钟= 24小时)。