UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Working on autosave method, looking for optimization ideas

Forums > Swift

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?

3      

Are you using a UIDocument subclass? That gets autosave for free if you set up change tracking and supply the proper handler.

4      

Ah, didn't know that! I haven't really worked with UIDocument yet; I've mostly been using Codable to export JSON via Data.write(to:) to save data from my applications so far. Will have to give that a closer look.

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.