Gabriele 和 tdevoy 的回答清楚地说明了为什么这是不可能的。所以我不会重复同样的事情,如果你不知道怎么做,你可以试试:
在你的,像这样viewDidLoad
存储登录时间NSUserDefaults
NSDate *currentDate= [NSDate date];
[[NSUserDefaults standardUserDefaults] setObject:currentDate forKey:@"loggedInTime"];
现在在您的applicationDidBecomeActive
委托方法中,
NSDate *loggedInTime = (NSDate *)[[NSUserDefaults standardUserDefaults] objectForKey:@"loggedInTime"];
NSTimeInterval timeSpentInApp = [[NSDate date] timeIntervalSinceDate:loggedInTime];
//if this timeSpentInApp is greater than 43200, then you can call logout.
//(Make sure after relogin, the loggedInTime value was updated again.)
但是,如果用户连续使用该应用程序 12 小时,那么您也应该考虑使用您的代码片段,因为这只会在应用程序来自后台时调用。