So I'm working on a notepad-style application, and I'm trying to work out an autosave-type function to save the user the need to explicitly save (as well as avoid the risk of losing data during a crash if the view doesn't disappear or the app doesn't go to the background).
So far I've got the following listener set in viewDidLoad()
:
NotificationCenter.default.addObserver(self, selector: #selector(autosave), name: UITextView.textDidChangeNotification, object: nil)
At the start of the function I've got the following logic to determine if we should proceed with the save or not:
// lastSaved is a private class property, set to Date?
if (isAutoSave) {
if let timestamp = lastSaved {
if (DateInterval(start: timestamp, end: Date()).duration < 3) {
print("Too soon for autosave")
return // Bail if it's been less than 3 seconds since the last auto-save
}
}
print("Proceeding with Autosave")
lastSaved = Date() // Set the date and proceed
}
Overall this is working pretty well, but there's one minor flaw in it—once the timer expires it requires another input to trigger the save. Is there a way to modify this so that we can set (and keep re-setting) a delay timer whenever a keypress is detected while editing the UITextView
and run the save when the timer expires?