Last active
February 27, 2018 14:05
-
-
Save arashkashi/9f1828eafd2c16a16c6abaaae13844c4 to your computer and use it in GitHub Desktop.
Detects the inactivity of a user based on a timer setup.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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