IOS开发—对当前屏幕闲置时间计时

实现:子类化UIWindow,并使app使用自定义的这个window。(也可以子类化UIApplication,修改main函数参数)

代码演示:屏幕闲置180s弹出手势密码解锁界面

//ICWindow.h文件
#import <UIKit/UIKit.h>
@interface ICWindow : UIWindow
/*! * 计时器是否可用(处在手势密码页时不可用) */
- (void)setTimerEnable:(BOOL)enable;

/*! * 停止闲置计时 */
- (void)stopIdleTiming;

/*! * 重新开始闲置计时 */
- (void)resetIdleTimer;
@end
//ICWindow.m文件
#import "ICWindow.h"
#import "GesturePasswordViewController.h"

@interface ICWindow ()

@property (nonatomic, assign) NSInteger idleTime;           //闲置时间
@property (nonatomic, assign) BOOL timeEnable;              //计时器是否可用

@end

@implementation ICWindow

- (void)sendEvent:(UIEvent *)event{
    [super sendEvent:event];

    // 只在开始或结束触摸时 reset 闲置时间, 以减少不必须要的时钟 reset 动作
    NSSet *allTouches = [event allTouches];

    if ([allTouches count] > 0) {
        // allTouches.count 似乎只会是 1, 因此 anyObject 总是可用的
        UITouchPhase phase =((UITouch *)[allTouches anyObject]).phase;
        if (phase ==UITouchPhaseBegan || phase == UITouchPhaseEnded)
            [self resetIdleTimer];
    }
}

- (void)resetIdleTimer {
    if (self.timeEnable == YES) {
        [self stopIdleTiming];
        self.idleTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(idleTimerexecuted) userInfo:nil repeats:YES];
    }
}

- (void)idleTimerexecuted {
    self.idleTime += 1;
    if (self.idleTime == 180) {
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSString *password = [userDefaults objectForKey:@"gesturePassword"];
        if (password) {
            //闲置180s 弹出手势密码界面
            GesturePasswordViewController *gesturePasswordVC = [[GesturePasswordViewController alloc]initWithNibName:@"GesturePasswordViewController" bundle:nil isCheck:YES];
            [self.rootViewController  presentViewController:gesturePasswordVC animated:YES completion:nil];
            [self setTimerEnable:NO];
        }
    }
}

- (void)stopIdleTiming{
    self.idleTime = 0;
    if (self.idleTimer) {
        [self.idleTimer invalidate];
        self.idleTimer = nil;
    }
}

- (void)setTimerEnable:(BOOL)enable{
    self.timeEnable = enable;
    if (!enable) {
        [self stopIdleTiming];
    }
}

@end

你可能感兴趣的:(ios开发,闲置计时)