我想检查应用程序是否空闲(用户在过去 30 分钟内未执行任何操作)并注销用户。
为此,我有一个重置计时器的事件管理器。
- (void)sendEvent:(UIEvent *)event {
if(event == nil) {
[self resetIdleTimer];
} else {
[super sendEvent:event];
// Only want to reset the timer on a Began touch or an Ended touch, to reduce the number of timer resets.
NSSet *allTouches = [event allTouches];
if ([allTouches count] > 0) {
// allTouches count only ever seems to be 1, so anyObject works here.
UITouchPhase phase = ((UITouch *)[allTouches anyObject]).phase;
if (phase == UITouchPhaseBegan || phase == UITouchPhaseEnded)
[self resetIdleTimer];
}
}
}
- (void)resetIdleTimer {
if (self.idleTimer) {
[self.idleTimer invalidate];
self.idleTimer = nil;
}
NSInteger maxTime = 60*30; //30 minutes
self.idleTimer = [NSTimer scheduledTimerWithTimeInterval:maxTime target:self selector:@selector(checkIfIdleTimerExceeded) userInfo:nil repeats:NO];
}
- (void)checkIfIdleTimerExceeded {
theProfileManager = [[ProfileManager alloc] init];
theProfile = [theProfileManager getProfile];
if( ! [[theProfile getStatus]isEqualToString:@"u1"]) {
if( ! [[theProfile getTheUser] isUnlimitedLogin]) {
theProfile = nil;
theUserManager = [[UserManager alloc] init];
[theUserManager setCurrentUser:[theProfile getTheUser]];
[theUserManager setCurrentUserAccount:[[theProfile getTheUser] getTheUserAccount]];
[theUserManager setCurrentUserSettings:[[theProfile getTheUser] getTheUserSettings]];
[theUserManager logoutCurrentUser];
[[MenuItemDataManager alloc] deleteJsonData];
NSNotification *msg = [NSNotification notificationWithName:@"leftPanelMsg" object:[[NSString alloc] initWithFormat:@"Home"]];
[[NSNotificationCenter defaultCenter] postNotification:msg];
[self performSelector:@selector(loadHomeView:) withObject:nil afterDelay:0.5f];
}
}
[self resetIdleTimer];
}
checkIfIdleTimerExceeded
执行注销过程。
问题:在我触摸屏幕 15 分钟后,resetIdleTime
被调用并且应该重新启动一个新的 NSTimer
。但 15 分钟后,应用程序将用户注销。
感谢您的帮助。
安德烈。
最佳答案
根据您对 Touches 事件的要求。你应该这样做:
NSSet *allTouchEvents = [event allTouches];
if ([allTouchEvents count] > 0) {
// allTouchEvents count only ever seems to be 1, so anyObject works here.
UITouchPhase phase = ((UITouch *)[allTouchEvents anyObject]).phase;
if (phase == UITouchPhaseBegan || phase == UITouchPhaseEnded)
[self resetIdleTimer];
}
而在resetIdleTimer中,
self.idleTimer = [NSTimer scheduledTimerWithTimeInterval:maxTime target:self selector:@selector(checkIfIdleTimerExceeded) userInfo:nil repeats:NO];
应该是这样
self.idleTimer = [NSTimer scheduledTimerWithTimeInterval:maxTime target:self selector:@selector(checkIfIdleTimerExceeded:) userInfo:nil repeats:NO];
checkIfIdleTimerExceeded
应该是这样的:
-(void) checkIfIdleTimerExceeded :(NSTimer*)timer
{
//Do your all process and invalidate after completion
[timer invalidate];
}
关于ios - NSTimer 在无效时不会停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24449592/