您的位置:首页 > 移动开发 > IOS开发

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

2017-08-11 10:36 274 查看
大部分银行客户端都有这样的需求,在用户一定时间内未操作,即认定为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])
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: