1

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!

Community
  • 1
  • 1
boidkan
  • 4,691
  • 5
  • 29
  • 43

2 Answers2

4

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)
}
matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Thanks man, this was a very simple solution! Sorry it took me so long to get to this but this functionality suddenly went very low on my priority list so it took me a while to get around to looking at the answers. – boidkan Nov 19 '14 at 21:05
  • @matt where is decrementScore method? and how would this code work as an idle time out concept? o.O thanks – ernestocattaneo Dec 23 '14 at 12:50
2

For each view controller you want to track the last user activity of, create a property with either a NSDate or a NSTimeInterval.

Then, make liberal use of either NSResponder or UIResponder (you didn't specify whether or not you're doing this in iOS or MacOS) methods in your view controller subclass, which is what each application, window and view is built on top of.

UIResponder, for example, has methods for "touchesBegan:withEvent:", and you can reset your view controller's date property each time a touch happens in the view.

Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215