1
我正在爲我的應用程序實現會話不活動狀態,以便如果用戶在30秒內不活動,則向他展示一個新的uiviewcontroller作爲表單。對於觸摸事件,我使用這個代碼觸摸在目標中被注意到兩次c
(void)sendEvent:(UIEvent *)event {
[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) {
[[BCDTimeManager sharedTimerInstance]resetIdleTimer];
}
}
}
在BCDTimeManager類,這是一個單獨的類我已經實現resetIdleTimer和idleTimerExceed方法
#import "BCDTimeManager.h"
@implementation BCDTimeManager
__strong static BCDTimeManager *sharedTimerInstance = nil;
NSTimer *idleTimer;
NSTimeInterval timeinterval;
+ (BCDTimeManager*)sharedTimerInstance
{
static dispatch_once_t predicate = 0;
dispatch_once(&predicate, ^{
sharedTimerInstance = [[self alloc] init];
NSString *timeout = [[NSUserDefaults standardUserDefaults] valueForKey:@"session_timeout_preference"];
timeinterval = [timeout doubleValue];
});
return sharedTimerInstance;
}
- (void)resetIdleTimer {
if (idleTimer) {
[idleTimer invalidate];
}
idleTimer = nil;
NSLog(@"timeout is %ld",(long)timeinterval);
idleTimer = [NSTimer scheduledTimerWithTimeInterval:timeinterval target:self selector:@selector(idleTimerExceeded) userInfo:nil repeats:true];
}
- (void)idleTimerExceeded {
NSLog(@"idle time exceeded");
[[NSNotificationCenter defaultCenter]
postNotificationName:@"ApplicationTimeout" object:nil];
}
但是當我做在屏幕上的任何觸摸,在控制檯,我可以看到NSLog打印了兩次,這導致我的NSNOtification動作被觸發兩次。
我不知道我在做什麼錯。請幫我弄清楚這一點。
你在''''resetIdleTimer'''中定義'''idleTimer''在哪裏?在我看來,當你調用''[idleTimer invalidate]'''時,它不存在。 – docksteaderluke
我已更新代碼,以顯示我在哪裏定義idleTimer – Nitya
有一件事是我在rootViewController中添加NSNotification觀察者,並在用戶註銷時刪除觀察者。是否有可能觀察員沒有正確移除並導致通知被添加兩次。 – Nitya