Skip to content

Instantly share code, notes, and snippets.

@gaelfoppolo
Last active July 23, 2017 21:15
Show Gist options
  • Save gaelfoppolo/08f4883cd308e1a37852479544eb5425 to your computer and use it in GitHub Desktop.
Save gaelfoppolo/08f4883cd308e1a37852479544eb5425 to your computer and use it in GitHub Desktop.
import UIKit
class TimerApplication: UIApplication {
// the timeout in seconds, after which should perform custom actions
// such as disconnecting the user
private var timeoutInSeconds: TimeInterval {
// 2 minutes
return 2 * 60
}
private var idleTimer: Timer?
// resent the timer because there was user interaction
private func resetIdleTimer() {
if let idleTimer = idleTimer {
idleTimer.invalidate()
}
idleTimer = Timer.scheduledTimer(timeInterval: timeoutInSeconds,
target: self,
selector: #selector(TimerApplication.timeHasExceeded),
userInfo: nil,
repeats: false
)
}
// if the timer reaches the limit as defined in timeoutInSeconds, post this notification
@objc private func timeHasExceeded() {
NotificationCenter.default.post(name: .appTimeout,
object: nil
)
}
override func sendEvent(_ event: UIEvent) {
super.sendEvent(event)
if idleTimer != nil {
self.resetIdleTimer()
}
if let touches = event.allTouches {
for touch in touches where touch.phase == UITouchPhase.began {
self.resetIdleTimer()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment