Skip to content

Instantly share code, notes, and snippets.

@arashkashi
Last active February 27, 2018 14:05
Show Gist options
  • Save arashkashi/9f1828eafd2c16a16c6abaaae13844c4 to your computer and use it in GitHub Desktop.
Save arashkashi/9f1828eafd2c16a16c6abaaae13844c4 to your computer and use it in GitHub Desktop.
Detects the inactivity of a user based on a timer setup.
extension Notification.Name {
public static let ProlongedInactivity = Notification.Name("ProlongedInactivity")
}
class UserInactivityDetector {
var idleTimeAllowed: TimeInterval = 30 {
didSet {
if enabled {
reinitThetimer()
} else {
workItem?.cancel()
}
}
}
private var workItem: DispatchWorkItem?
var enabled: Bool = true {
didSet {
if enabled {
reinitThetimer()
} else {
workItem?.cancel()
}
}
}
init() {
NotificationCenter.default.addObserver(self, selector:#selector(onUserActivity), name: Notification.Name.SentEvent, object: nil)
reinitThetimer()
}
func sendInactivityNotification() {
NotificationCenter.default.post(name: Notification.Name.ProlongedInactivity, object: nil)
}
func reinitThetimer() {
workItem?.cancel()
workItem = DispatchWorkItem(block: { [weak self] in
self?.sendInactivityNotification()
})
if let valid = workItem {
DispatchQueue.main.asyncAfter(deadline: .now() + idleTimeAllowed, execute: valid)
}
}
@objc func onUserActivity() {
reinitThetimer()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment