ios - iPhone:检测自上次屏幕触摸以来的用户不活动/空闲时间

有没有人实现了一个功能,如果用户在一段时间内没有触摸屏幕,你就会采取某种行动?我正在尝试找出最好的方法。

在 UIApplication 中有这个有点相关的方法:

[UIApplication sharedApplication].idleTimerDisabled;

如果你有这样的东西就好了:

NSTimeInterval timeElapsed = [UIApplication sharedApplication].idleTimeElapsed;

然后我可以设置一个计时器并定期检查这个值,并在它超过阈值时采取一些措施。

希望这能解释我在寻找什么。有没有人已经解决了这个问题,或者对你将如何做有任何想法?谢谢。

最佳答案

这是我一直在寻找的答案:

让您的应用程序委托(delegate)子类 UIApplication。在实现文件中,重写 sendEvent: 方法,如下所示:

- (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)
            [self resetIdleTimer];
    }
}

- (void)resetIdleTimer {
    if (idleTimer) {
        [idleTimer invalidate];
        [idleTimer release];
    }

    idleTimer = [[NSTimer scheduledTimerWithTimeInterval:maxIdleTime target:self selector:@selector(idleTimerExceeded) userInfo:nil repeats:NO] retain];
}

- (void)idleTimerExceeded {
    NSLog(@"idle time exceeded");
}

其中 maxIdleTime 和 idleTimer 是实例变量。

为了让它工作,你还需要修改你的 main.m 来告诉 UIApplicationMain 使用你的委托(delegate)类(在这个例子中,AppDelegate)作为主体类:

int retVal = UIApplicationMain(argc, argv, @"AppDelegate", @"AppDelegate");

https://stackoverflow.com/questions/273450/

相关文章:

iphone - 以编程方式切换到 TabBar 选项卡 View ?

ios - 两个 NSDate 之间的天数

objective-c - xcode中Base SDK、iOS部署目标、Target、Projec

ios - 如何手动弃用成员

ios - 如何确定 NSDate 是否是今天?

ios - 从 UIColor 创建 UIImage 以用作 UIButton 的背景图像

objective-c - 为什么要使用 ivar?

ios - 如何查看 NSString 是否以某个其他字符串开头?

ios - 如何在 iPhone 上创建圆角 UILabel?

objective-c - 在objective-c中YES/NO,TRUE/FALSE和true/