Search code examples
swiftappdelegateidle-timer

Detecting user inactivity in any VC


I need to be able to keep track of the last user activity (touch on screen). I found this question and answer here however this does not work for me in swift at all. idleTimer.release is not a thing and I just get an error. Also, I am assuming that you have to create an NSTimer since idleTimer is not a thing either unless you make it. I am also confused by the line

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

So, how can I accomplish this in swift? A bit frustrated!


Solution

  • Here's how I do it in my app. Create the timer to check every so often:

    self.timer = NSTimer.scheduledTimerWithTimeInterval(
        10, target: self, selector: "decrementScore", userInfo: nil, repeats: true)
    

    Now we know that if decrementScore() is called, 10 seconds of idle time went by. If the user does something, we need to restart the timer:

    func resetTimer() {
        self.timer?.invalidate()
        self.timer = NSTimer.scheduledTimerWithTimeInterval(
            10, target: self, selector: "decrementScore", userInfo: nil, repeats: true)
    }