iOS超时功能不能正常工作



我添加了这段代码,它在我的应用程序中充当自动超时。userDefaults doubleForKey:@"timeoutLength"应该在几分钟内完成。例如,如果value为500,则表示500分钟。

我似乎一直在打超时循环,即使它还没有真正的500 +分钟。是什么错误在我的代码?可能是分/秒错误等

    [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;
}

NSTimeInterval以表示,而不是分钟。

这是苹果文档中对它的描述。

我不能100%确定你的终极问题是什么,但是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小时)

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

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

相关内容

  • 没有找到相关文章

最新更新