ios - 如何在检测到自上次屏幕触摸后用户不活动/空闲时间时注销应用程序

标签 ios objective-c iphone

我想在我的应用程序中添加注销功能,以便用户在自上次屏幕触摸后的不活动/空闲时间得到注销。

请建议我实现此功能的方法。

有些人告诉你在你的代码中添加这个;

- (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");

    }

但我的问题是在哪里添加这段代码。

最佳答案

摆脱所有计时器代码,只需执行此操作即可。当用户点击时,安排您的空闲方法在 X 秒后调用(使用 performSelector: afterDelay:)。每当他们点击时,取消所有计划的请求(使用 cancelPreviousPerformRequestsWithTarget:)并在 X 秒内请求一个新请求。

int secondsUntilTimeout = 120;//time you want until they time-out.

[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(idleTimerExceeded) object:nil];//cancel all previously scheduled time-out requests

[self performSelector:@selector(idleTimerExceeded) withObject:nil afterDelay:secondsUntilTimeout];//schedule a new time-out request

因此您的最终代码将如下所示:

- (void)sendEvent:(UIEvent *)event {
    [super sendEvent:event];
    NSSet *allTouches = [event allTouches];
    if ([allTouches count] > 0) {
        UITouchPhase phase = ((UITouch *)[allTouches anyObject]).phase;
        if (phase == UITouchPhaseBegan || phase == UITouchPhaseEnded) {

            int secondsUntilTimeout = 120;//time you want until they time-out.

            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(idleTimerExceeded) object:nil];//cancel all previously scheduled time-out requests

            [self performSelector:@selector(idleTimerExceeded) withObject:nil afterDelay:secondsUntilTimeout];//schedule a new time-out request

        }
    }
}


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

关于ios - 如何在检测到自上次屏幕触摸后用户不活动/空闲时间时注销应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45474943/

相关文章:

ios - TableView reloadData 与 beginUpdates & endUpdates

ios - 在 UIView 后面捕获(动画)屏幕

ios - 如何检测应用程序是否从 xcode 启动?

iphone - 自定义 UIView 的文本选择和放大镜实现

iphone - 在 NSPredicate 更改后使用 NSFetchedResultsControllerDelegate 更新 TableView 部分和行

ios - 无法调用 Alamofire.request(...)

ios - 为什么我不能在数组中附加标签?

ios - 无法实现核心图条形图中条形颜色的更改

ios - 来自指针的 PFFile 抛出异常