iOS实现程序长时间未操作退出

大部分银行客户端都有这样的需求,在用户一定时间内未操作,即认定为token失效,但未操作是任何判定的呢?我的想法是用户未进行任何touch时间,原理就是监听runloop事件。我们需要进行的操作是创建一个UIApplication的子类,废话不多说,上代码

// 定义未操作通知的时间,也可以从服务器上获取。
#define kApplicationTimeoutInMinutes 30

@interface NTApplication : UIApplication {
    NSTimer *_myTimer;
}

- (void)resetTimer;

@end
@implementation NTApplication

- (void)sendEvent:(UIEvent *)event {
    
    [super sendEvent:event];
    
    if (!_myTimer) {
        
        [self resetTimer];
        
    }
    NSSet *allTouches = [event allTouches];
    
    if ([allTouches count] > 0) {
        
        UITouchPhase phase = ((UITouch *)
                             
                             [allTouches anyObject]).phase;
        
        if (phase ==UITouchPhaseBegan) {
            [self resetTimer];
        }
        
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:kUserBreakFreeNotification object:nil];
}

//重置时钟

- (void)resetTimer {
    
    if (_myTimer) {
        
        [_myTimer invalidate];
        
    }
    
    int timeout = kApplicationTimeoutInMinutes;//超时时间,我这里设置为30s
    
    _myTimer = [NSTimer scheduledTimerWithTimeInterval:timeout target:self selector:@selector(freeTimerNotificate:) userInfo:nil repeats:NO];
    
}

//当达到超时时间,发送 kApplicationTimeoutInMinutes通知

- (void)freeTimerNotificate:(NSNotification *)notification {
    //在想要获得通知的地方注册这个通知就行了
    [[NSNotificationCenter defaultCenter] postNotificationName:kUserEnterFreeTimeoutNotification object:nil];
}

@end

还有最重要的一部,将NTApplication与当前的AppDelegate关联起来,在main.m中更改

 

#import "NTApplication.h"

int main(int argc, char * argv[]) {
    @autoreleasepool {
        return UIApplicationMain(argc, argv, NSStringFromClass([NTApplication class]), NSStringFromClass([AppDelegate class]));
    }
}

 

UIApplicationMain原来的第三个参数是nil,更改成NSStringFromClass([NTApplication class])

 

posted @ 2017-08-11 10:36  小白猪jianjian  阅读(1295)  评论(0编辑  收藏  举报