Last Updated: December 26, 2018
·
8.506K
· novalagung

iOS - Perform action if there is no user interaction in specific duration

First, create constant for handling timeout duration in seconds, and NSTimer instance for idle detection.

// in your SomeViewController.h file
// ...

#define kTimeoutUserInteraction 3

// ...

NSTimer *idleTimer;

In .m, adding these functions

// in your SomeViewController.m file
// ...

# pragma mark timer

- (void)resetIdleTimer {
    if (!idleTimer) {
        idleTimer = [NSTimer scheduledTimerWithTimeInterval:kTimeoutUserInteraction target:self selector:@selector(idleTimerExceeded) userInfo:nil repeats:NO];
        [[NSRunLoop currentRunLoop] addTimer:idleTimer forMode:NSDefaultRunLoopMode];
    } else {
        if (fabs([idleTimer.fireDate timeIntervalSinceNow]) < kTimeoutUserInteraction - 1.) {
            idleTimer.fireDate = [NSDate dateWithTimeIntervalSinceNow:kTimeoutUserInteraction];
        }
    }
}

- (void)idleTimerExceeded {
    idleTimer = nil;
    // do something
    [self resetIdleTimer];
}

- (UIResponder *)nextResponder {
    [self resetIdleTimer];
    return [super nextResponder];
}

// ...

in short, nextResponder is called in every user interaction. In resetIdleTimer, idleTimer is checked wether it's outdate or not, idleTimer going to be renewed if it's outdated. \\ do something is called when timer is exceeded.